Undefined reference error

When I ran g++ practice.cpp -o practice I got an undefined reference error.

To resolve the problem, I changed the compile command to: g++ practice.cpp Greetings.cpp -o practice Greeting.cpp contains the method implementations of the Greeting class, which is included in practice.cpp

While I was able to resolve the problem, I don't understand why I needed to add the method implementation file (Greetings.cpp) in the compile cmd. Shouldn't it be automatically added?

P.S.

Thanks Chewbob, I edited/re-posted right after you submitted the answer to my *original* question. But my follow-up question is still unanswered.
Last edited on
I think you need to compile Greetings.cpp as well. I've not used GCC but maybe compile with g++ *.cpp -o practice or g++ practice.cpp greetings.cpp -o practice or something like that.
Last edited on
Looks like you are also trying to link the file as well.

In your example above try the c (compile but do not link) option for g++

g++ -c practice.cpp -o practice
I tried: g++ -c practice.cpp -o practice and the code compiled creating an anonymous type file.

However, when I tried: g++ -c practice.cpp -o practice.exe the code compiled and an executable was created; when I ran the executable, it froze my computer.
Or just g++ -c practice.cpp - IIRC g++ will automatically name the resulting object file
practice.o
.

But note that you are only creating an object file with the -c option NOT an exe - so there is no point in giving it an exe extension and trying to run it.
closed account (oG8U7k9E)
...
Last edited on
@guestgulkan

I unfortunately, overlooked your
(compile but do not link)
clarification in your post, thus leading to my confused follow-up post. I appreciate the help.

@audit
I can not think of anyway for the complier to know what files need to be compiled if you do not specify them.

I was under the impression that since I had included the header file in the file being compiled, the compiler would automatically compile & link the corresponding implementation file. As it turns out, the implementation file needs to be specified.
Topic archived. No new replies allowed.