LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   linking and compiling multiple c++ files into one (https://www.linuxquestions.org/questions/programming-9/linking-and-compiling-multiple-c-files-into-one-776405/)

skazhy 12-17-2009 07:39 AM

linking and compiling multiple c++ files into one
 
Hi!

I have 3 c++ files, classdef.h (header file with class definition), methods.cpp (class methods) and program.cpp - the program itself. Both .cpp files have
Code:

#include "classdef.h"
in files.

How I can link the files together and compile them in one executable program? I am using Geany IDE for coding.

Thanks in advance,

-skazhy

MTK358 12-17-2009 09:40 AM

I don't know about Geany, but with gcc:

Code:

g++ -o program program.cpp methods.cpp
The "-o program" flag causes the executable to be named "program" instead of the default "a.out".

g++ will automatically include the necessary .h files.

Don't know if this will help.

johnsfine 12-17-2009 09:55 AM

The g++ program is a supervisor that invokes the compiler and linker for you.

The operation
Code:

g++ -o program program.cpp methods.cpp
tells it to independently:
compile program.cpp
compile methods.cpp
link the two results together plus startup code and default libraries.

With compilers on many other platforms, including two cpp files in one compile command would tell the compiler to compile the concatenated source code, rather than compile separately. That is rarely what you want, so on such systems, you would issue the two separate compile commands followed by the link command.

Even with GCC, you may prefer to give compile and link commands separately:
Code:

g++ -c program.cpp
g++ -c methods.cpp
g++ -o program program.o methods.o

Most IDEs manage all that for you (generate that sequence of separate g++ commands, or more commonly generate a makefile then issue a make command to issue the right sequence of g++ commands). I have no idea what Geany does for that.

If you want Geany to generate the g++ commands for you, read its documentation and/or put "Geany" in the topic of your thread so someone who knows it is more likely to respond.

MTK358 12-17-2009 10:08 AM

Quote:

Originally Posted by johnsfine (Post 3795509)
Even with GCC, you may prefer to give compile and link commands separately:
Code:

g++ -c program.cpp
g++ -c methods.cpp
g++ -o program program.o methods.o


I often do it that way, it helps with debugging.

skazhy 12-18-2009 03:43 AM

thank you very much guys, this info was very helpful :)


All times are GMT -5. The time now is 03:27 AM.