Undefined reference error

Sep 17, 2009 at 9:52pm
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 Sep 17, 2009 at 10:26pm
Sep 17, 2009 at 10:18pm
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 Sep 17, 2009 at 10:19pm
Sep 17, 2009 at 10:23pm
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
Sep 17, 2009 at 10:33pm
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.
Sep 17, 2009 at 10:41pm
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.
Sep 17, 2009 at 11:01pm
closed account (oG8U7k9E)
...
Last edited on Oct 4, 2009 at 1:56pm
Sep 18, 2009 at 8:04pm
@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.