View Full Version : C++ compile / link files

Mar 30, 2009, 09:18 AM

I am a newbie to c++, I would like to compile / link c++ files:

game.h (header / interface file)
game.cpp (implementation of the header file)
use_game.cpp (a program file that uses the definitions of the functions in game.cpp)

How would I compile the above in the terminal ?

I used to use g++ for compiling simple (one source code file).


Mar 30, 2009, 10:26 AM
GCC lets you provide multiple source files on the same command line, so you could simply do

g++ -o mygame -Wall game.cpp use_game.cpp

Mar 30, 2009, 10:30 AM

Assuming the files are within the same folder. Substitute the desired name of the compiled executable for "gameApp" in following terminal command:

g++ -o gameApp game.cpp use_game.cpp

Mar 30, 2009, 12:44 PM
Thanks Sander and Dydx

Works Great !!!

I was under the impression, that the game.cpp and use_game.cpp need to be compiled separately. Then the object code of the 2 files needed to be linked.

I think g++ does that in one step, correct me if I am wrong.

Mar 30, 2009, 01:23 PM
I think g++ does that in one step, correct me if I am wrong.

It still does each step, but it does it for you with one command.


Mar 31, 2009, 05:57 AM
Thanks all for all your replies, really helped.

One more doubt:
Header files (game.h) are in the directory $HOME/c++/header
Implementation files (game.cpp) are in the directory $HOME/c++/implementation
Application files (use_game.cpp) are in the directory $HOME/c++/application

How do I compile in this case ?
How can I tell the compiler that the header is present in a specific directory ?

Hope I am not being unreasonable.
Somehow the compiler knows where the predefined header files are though it is not in the same of the source directory

Apr 6, 2009, 02:40 AM
You can add directories to the header file search path with the -I command line switch.