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 you can see, there are several folders with several source files. What command do I give g ++ to compile the entire source file into a single .o file?

+5
source share
4 answers

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

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

%.o : $(SRC_FOLDER)/%.cpp
  $(CXX) -c -o $@ $<
+5
source

, makefile . , , make . , . Scons, GNU autotools, qmake Cmake, . qmake Cmake, - .

, , - IDE! c++ IDE Linux, , -, - Qt Creator. qmake Cmake.

+2

Visual Studio, Linux, ;)

GradGuy, QtCreator - , - . , - GUI, cmake, Qt .

cmake - (, VS.sln ), , IDE . , , .

, .

  • qtcreator cmake
  • cmake, .
  • CMakeLists.txt src :

    project( myProject )
    
    # set your include directories (if you have any)
    include_directories( include )
    
    # tell cmake what what are your source files
    set( MY_CPP_FILES 
        src/source1.cpp
        src/source2.cpp
        src/srcfolder1/source11.cpp
        src/srcfolder1/source12.cpp
        src/srcfolder2/source21.cpp
        src/srcfolder2/source22.cpp )
    
    # if you are creating an executable then do so like this
    # note that ${MY_CPP_FILES} will replace it with its content
    add_executable( myExec ${MY_CPP_FILES} )
    
    # if you instead want a library, do it like so
    add_library( myStaticLib STATIC ${MY_CPP_FILES} ) # create a static library
    add_library( mySharedLib SHARED ${MY_CPP_FILES} ) # create a shared library
    
  • now run QtCreator and select File -> Open File or Projectand select CMakeLists.txton your disk

  • Now you will be asked to choose the path in which the results will be saved (as well as all intermediate files).
  • hit Run CMake
  • and finally select Build -> Build All

Good luck

+1
source

Perhaps the most direct answer is something like:

g++ $(find src -name '*.cpp')

However, with so many translation modules, having a Makefile can significantly reduce build time when editing source files and building for testing.

0
source

All Articles