Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple source files to create a single object file with gcc

Tags:

c++

object

gcc

g++

I'm using the -c option with g++ to create a bunch of object files, and it's only letting me specify one source file for each object file. I want to have multiple files go into some of them. Is there any way to do this?

like image 653
David Avatar asked Jun 27 '11 07:06

David


People also ask

How do we implement multiple source program files?

Split the program into three files, main. c, which contains main(), node. h, the header which ensures declarations are common across all the program, and hence is understood by the compiler, and node. c, the functions which manipulate the NODE structure.


2 Answers

Others have mentioned archive, but another option is Unity builds.

Instead of:

g++ -c file1.cpp file2.cpp

Create a separate "unity file"

// This is the entire file (unity.cpp)
#include "file1.cpp"
#include "file2.cpp"
// more if you want...

Then

g++ -c unity.cpp

This also has the advantage of faster compilation and linking in many cases (because headers used by both file1.cpp and file2.cpp are only parsed once). However, if you put too many files in a single unity however then you'll find that you need to rebuild more sources than you wanted to, so you need to try and strike a balance.

like image 84
Peter Alexander Avatar answered Sep 17 '22 19:09

Peter Alexander


You can use ld -r to combine the objects while keeping relocation information and leaving constructors unresolved:

ld -r -o everything.o object1.o object2.o ...
like image 30
Simon Richter Avatar answered Sep 20 '22 19:09

Simon Richter