Home >Backend Development >C++ >How to Compile Multiple C Files Using g : Makefile or Single Command?
Compiling Multiple C Source and Header Files Using G
You have inherited a poorly written C codebase that includes a single .cpp file containing the main function and other program logic, along with multiple .h files containing class definitions. Previously, the code was compiled using the g main.cpp command.
As you have now separated the classes into individual .h and .cpp files, you need to determine if you still need to use a Makefile or if you can continue using the g main.cpp command for compilation.
To compile multiple source files using g , you can simply list all the .cpp files that you want to include in the program, as shown below:
g++ main.cpp other.cpp etc.cpp
This command will create an executable file that includes the code from all the specified source files.
Alternatively, you can first compile each source file individually into object files (.o files):
g++ -c main.cpp g++ -c other.cpp g++ -c etc.cpp
Then, you can link the object files together to create the executable:
g++ main.o other.o etc.o -o executable_name
Choosing between these two methods depends on your preference and the size of your codebase. If you have a small number of source files, then using the single g command to compile them all together may be more convenient. For larger codebases, using a Makefile to manage the compilation process can be more efficient and help prevent recompilation of unchanged files.
The above is the detailed content of How to Compile Multiple C Files Using g : Makefile or Single Command?. For more information, please follow other related articles on the PHP Chinese website!