C++ Undefined Symbol – Simple program that is erroring with external function declaration [duplicate]

  c++, undefined, xcode

I’m new to C++, and just learning by doing something that is keeping me interested. But I’ve come across this really weird issue that I can’t resolve for the life of me.

I’ve written a few classes, and everything is working fine, but when I build out some functions into the .cpp file (external declaration, I believe is the right time) – I get an error message saying "Undefined symbol".

I thought it was a combination of forward declaration / includes / cross-dependencies, because I had this earlier in the project, but this seems not that.

Just to be clear, if I make the declaration inline, it works absolutely fine.

To try and find the cause, I made a copy of the Xcode project and removed all the classes one-by-one, all to no avail, so what I’m left with is this:

main.cpp

#include "print_string.hpp"

int main()
{
    print_string x{};
    x.print_str("Hello!");
    x.sqr(5);
    
    return 0;
}

print_string.cpp

#include "print_string.hpp"

int print_string::sqr(int x)
{
    return x * x;
}

print_string.hpp

#ifndef print_string_hpp
#define print_string_hpp

#include <iostream>
#include <stdio.h>
#include <string>

class print_string
{
public:
    void print_str(std::string str) { std::cout << "String: " << str << std::endl; };
    int sqr(int x);
};

#endif

To try and resolve this issue, I thought I was doing something noddy, so I wrote a similar basic program (completely clean project) and it worked fine – so I think it may be my project that has broken, but I literally have nothing else left in this copy of the project other than the above. Cleaned the build folder, etc but not sure what else I can do.

In summary, if I run this project with the x.sqr(5); call, I get the error. If I comment it out, it works absolutely fine.

Source: Windows Questions C++

LEAVE A COMMENT