Is it a good idea to include .cpp files instead of .h files to make vanilla gcc able to optimize my code more?

c++, coding-style, gcc

Solution

This practice is called "Unity Build" (google it) and is generally not a good idea for anything but trivial projects since you will need to recompile the entire project every time you make a single change, which can mean minutes of waiting every time you fix a tiny error.

As for runtime performance, the difference in speed is not very different from compiling with Link Time Optimizations on.

Problem

Is it a good idea to use `#include "randombytes.cpp"` instead of `randombytes.h` in my project (where `randombytes.cpp` is a file in my projects source code directory) for runtime speed reasons? `randombytes.cpp` would look like this: ``` #ifndef RANDOMBYTES_INCLUDED #define RANDOMBYTES_INCLUDED /* include native headers here */ unsigned char *fetch_random_bytes(int amount); /* include other parts of my project here if necessary */ unsigned char *fetch_random_bytes(int amount) { // do stuff } #endif ``` This should also work for files requiring each other and so on, right? Can you think of any cases in which this won't work or I won't get the optimization benefit?

Original source

Related problems