3

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?

Community
  • 1
  • 1
thejh
  • 44,854
  • 16
  • 96
  • 107
  • See if your linker supports Link Time Code Generation (or similar). If it does, you probably don't need such a hack. – Alexandre C. Apr 21 '12 at 15:26
  • No, it's not a good idea. You should probably just put the functions you want to be inlined inside the headers. – Niklas B. Apr 21 '12 at 15:26

2 Answers2

7

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.

Hampus Nilsson
  • 6,692
  • 1
  • 25
  • 29
2

yes, this is in generally a technique called 'unity builds' and it helps in the inlining process (if the compiler is smart enough). However there are disadvantages of this if you have duplicate functions with internal linkage (i.e: functions that only exist in the .cpp and are not declared in a .h), since those might give hard to debug compile errors, althought that can be avoided with careful and consistent naming conventions

some reading regarding this:

The benefits / disadvantages of unity builds?

http://www.gmixer.com/archives/46

Community
  • 1
  • 1
lurscher
  • 25,930
  • 29
  • 122
  • 185