简体   繁体   English

包含.cpp文件而不是.h文件以使vanilla gcc能够更多地优化我的代码是一个好主意吗?

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

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 ? 出于运行速度的原因 ,在我的项目中使用#include "randombytes.cpp"而不是randombytes.h (其中randombytes.cpp是我的项目源代码目录中的文件)是一个好主意吗? randombytes.cpp would look like this: randombytes.cpp看起来像这样:

#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? 你能想到任何不起作用的情况,或者我不会得到优化的好处吗?

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. 这种做法被称为“Unity Build”(google it),除了琐碎的项目之外通常不是一个好主意,因为每次进行一次更改都需要重新编译整个项目,这可能意味着每次你都要等待几分钟修复一个小错误。

As for runtime performance, the difference in speed is not very different from compiling with Link Time Optimizations on. 至于运行时性能,速度差异与使用链接时间优化进行编译没有太大差别。

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 (ie: 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 但是,如果您具有内部链接的重复函数(即:仅存在于.cpp中并且未在.h中声明的函数),则存在这样的缺点,因为这些可能难以调试编译错误,尽管可以避免具有仔细和一致的命名约定

some reading regarding this: 关于此的一些解读:

The benefits / disadvantages of unity builds? 团结的利弊是什么?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM