Using cmake
You can either write a makefile, which would contain all the files to be compiled in a folder or for a better management you can use cmake to compile all the files into a library and use them again. By using cmake you can efficiently maintain and build a huge code base.
Lets say, your Main directory has the main.cpp file and inside it has a src folder which has all other files to be compiled ,
Then You can create a CMakeLists.txt
file with following contents
set(CMAKE_C_COMPILER "gcc")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O2 -std=c++14 ")
add_subdirectory(src)
add_executable(main main.cpp)
target_link_libraries(main compiledLibrariesfrmSrcFolder)
Then Navigate inside your src
directory to create one more CMakeLists.txt. This will control all the files that you need to compileand add to your main program.
add_library(compiledLibrariesfrmSrcFolder STATIC
a.cpp
b.cpp
c.cpp
d.cpp)
Else, you could also use GLOB_RECURSE
to add all the .cpp files in that subdirectory
Once this is done, then you could create a new folder in your home directory and run the following
mkdir build
cd build
cmake ../
make
This compiles and generates your executable in the build folder.
Note : Just to elaborate more, The main reason to do this inside a build is because cmake creates lots of temp files during the process, To isolate them from your main code you will do the build inside the build directory.
cmake ../
, Here the cmake accepts a parameter which is the location of the main CMakeLists.txt
file. In our case it will be a directory before build. This creates the MakeFile
which has instructions to compile and link all the other necessary files.
make
compiles and links the files and generates the executables.