Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to minimize compilation time in C++

Tags:

c++

I've coded an script that generates a header file with constants like version, svn tag, build number. Then, I have a class that creates a string with this information.

My problem is the following: As the file is created in every compilation, the compiler detects that the header has changed, and forces the recompilation of a large number of files. I guess that the problem is in the situation of the header file. My project is a library and header has to be in the "interface to the world" header file (it must to be public).

I need some advice to minimize this compilation time or to reduce the files forced to recompile.

like image 603
Killrazor Avatar asked Feb 02 '11 10:02

Killrazor


People also ask

Why does compiling take so long?

Every single compilation unit requires hundreds or even thousands of headers to be (1) loaded and (2) compiled. Every one of them typically has to be recompiled for every compilation unit, because the preprocessor ensures that the result of compiling a header might vary between every compilation unit.

What is compile time optimization?

Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources or executes faster.


3 Answers

In the header write something like:

extern const char *VERSION;
extern const char *TAG;
extern const char *BUILD_DATE;

and create a .c (or .cpp) file that will contain

const char *VERSION = "0.13";
const char *TAG = "v_0_13";
const char *BUILD_DATE = "2011-02-02 11:19 UTC+0100";

If your script updates the .c file, only that file will have to be recompiled, but the files that include your header won't.

like image 170
Andrea Bergia Avatar answered Oct 03 '22 10:10

Andrea Bergia


Generate the constants in the implementation file.

Make sure the header doesn't get changed by your script.

like image 43
Eddy Pronk Avatar answered Oct 03 '22 08:10

Eddy Pronk


The easiest way to solve this is to not make those constants in a header file. Instead, make functions in the header file which get these values. Then place the values themselves in a small cpp file which implements those functions. (Or place them in a header ONLY included in that cpp file). When you recompile, only that one file will need to be recompiled.

Also, you could look in to distcc to speed up compilation if you have a few machines to spare.

like image 23
SoapBox Avatar answered Oct 03 '22 10:10

SoapBox