0

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
thnom
  • 35
  • 6
  • 1
    The code looks fine (except that you should not be using `` in C++, use `` instead, or not at all). What is the EXACT error message? Is `print_string.cpp` actually in your project? Is it being compiled into an object file, and is that object file being linked into the final executable? – Remy Lebeau Feb 23 '21 at 22:07
  • 1
    I'm guessing your compiler isn't configured to compile print_string.cpp. – Ruzihm Feb 23 '21 at 22:08
  • I've figured it out! I created a duplicate project and then got the same error message but noted that my "target" within Xcode when adding new files was deselected - so the project wasn't seeing the cpp file(s). Resolves me issue and now know where to turn it on! Also will look into stdio, not even sure I use it - default there when creating new files in Xcode. – thnom Feb 23 '21 at 22:44

0 Answers0