与c#和Java相比,编译c++文件需要很长时间。编译一个c++文件比运行一个正常大小的Python脚本花费的时间要长得多。我目前使用vc++,但它与任何编译器是一样的。为什么会这样?

我能想到的两个原因是加载头文件和运行预处理器,但这似乎不能解释为什么需要这么长时间。


当前回答

一些原因是:

1) c++语法比c#或Java更复杂,需要更多的时间来解析。

2)(更重要的是)c++编译器生成机器代码,并在编译期间进行所有优化。c#和Java只走了一半,将这些步骤留给JIT。

其他回答

另一个原因是使用C预处理器来定位声明。即使使用了头保护,.h仍然必须在每次包含它们时被反复解析。一些编译器支持预编译的头文件,可以帮助解决这个问题,但它们并不总是被使用。

参见:c++常见问题答案

Most answers are being a bit unclear in mentioning that C# will always run slower due to the cost of performing actions that in C++ are performed only once at compile time, this performance cost is also impacted due runtime dependencies (more things to load to be able to run), not to mention that C# programs will always have higher memory footprint, all resulting in performance being more closely related to the capability of hardware available. The same is true to other languages that are interpreted or depend on a VM.

在大型c++项目中减少编译时间的一个简单方法是创建一个包含项目中所有cpp文件的*.cpp包含文件并编译该文件。这将头爆炸问题减少到一次。这样做的好处是,编译错误仍然会引用正确的文件。

例如,假设你有a.cpp, b.cpp和c.cpp。创建一个文件:everything.cpp:

#include "a.cpp"
#include "b.cpp"
#include "c.cpp"

然后通过将everything.cpp编译项目

c++被编译成机器代码。所以你有预处理器,编译器,优化器,最后是汇编器,所有这些都必须运行。

Java和c#被编译成字节码/IL, Java虚拟机/。NET框架执行(或JIT编译成机器代码)之前执行。

Python是一种解释型语言,它也被编译成字节码。

我相信还有其他原因,但总的来说,不需要编译为本机机器语言可以节省时间。

编译语言总是比解释语言需要更大的初始开销。此外,也许您没有很好地组织您的c++代码。例如:

#include "BigClass.h"

class SmallClass
{
   BigClass m_bigClass;
}

编译速度比:

class BigClass;

class SmallClass
{
   BigClass* m_bigClass;
}