C++ compile / link files

Discussion in 'Mac Programming' started by muthuveerappan, Mar 30, 2009.

  1. macrumors newbie

    Joined:
    Aug 17, 2008
    Messages:
    15
    #1
    Hi,

    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).

    Thanks,
    Muthu
     
  2. macrumors 6502

    Joined:
    Apr 24, 2008
    Messages:
    471
    #2
    GCC lets you provide multiple source files on the same command line, so you could simply do

    Code:
    g++ -o mygame -Wall game.cpp use_game.cpp
    
     
  3. macrumors newbie

    Joined:
    Mar 30, 2009
    Messages:
    2
    #3
    muthuveerappan,

    Assuming the files are within the same folder. Substitute the desired name of the compiled executable for "gameApp" in following terminal command:
    Code:
    g++ -o gameApp game.cpp use_game.cpp
    
     
  4. macrumors newbie

    Joined:
    Aug 17, 2008
    Messages:
    15
    #4
    Thanks a ton !!!!

    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.
     
  5. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Messages:
    3,172
    Location:
    Dallas, TX
    #5
    It still does each step, but it does it for you with one command.

    -Lee
     
  6. macrumors newbie

    Joined:
    Aug 17, 2008
    Messages:
    15
    #6
    One more doubt

    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
     
  7. macrumors 6502

    Joined:
    Apr 24, 2008
    Messages:
    471
    #7
    You can add directories to the header file search path with the -I command line switch.
     

Share This Page