Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling multiple source directories with g++

My c++ project has the following structure

src
|
|source1.cpp
|source2.cpp
|
|<srcfolder1>
|__ source11.cpp
|__ source12.cpp
|
|<srcfolder2>
|__ source21.cpp
|__ source22.cpp

As can be seen there are multiple folders with multiple source files. What command do i give g++ to compile all the source file into a single .o file?

like image 596
pdeva Avatar asked Mar 24 '12 10:03

pdeva


People also ask

What does G do in compiling?

(debug) Inserting the `g' flag tells the compiler to insert more information about the source code into the executable than it normally would.

Where does C search for header files?

GCC looks for headers requested with #include " file " first in the directory containing the current file, then in the directories as specified by -iquote options, then in the same places it would have looked for a header requested with angle brackets.


2 Answers

If you have many source files you should really consider writing a Makefile: http://mrbook.org/tutorials/make/

You can for example use a syntax similar to this to compile multiple files (in the Makefile):

%.o : $(SRC_FOLDER)/%.cpp
  $(CXX) -c -o $@ $<
like image 74
Rolle Avatar answered Sep 18 '22 23:09

Rolle


You could also use build systems that would generate the actual makefile for you. This becomes important as you try to expand your project and maintaining a good makefile might become a daunting task. I suggest that you spend some time to learn one. Examples are Scons, GNU autotools, qmake, and Cmake, among others. I highlly reccomond the use of qmake or Cmake as they are both cross-platform and easy to learn.

Another option that you have is to simply use an IDE! The best c++ IDE on Linux that I know of, and is cross-platform, is Qt Creator. Under the hood it supports both qmake and Cmake projects.

like image 20
mmirzadeh Avatar answered Sep 20 '22 23:09

mmirzadeh