0

我正在使用代码块 IDE 和 GNU GCC 编译器。当我创建一个简单的程序,例如 add.cpp (用于添加两个数字)时,它通常会根据其中一些文件 add.exe(执行文件) add.o(目标文件)创建两个文件 add.o 链接到 add.exe在执行时。我的问题是我删除了 add.o 仍然 add.exe 正在执行并且仍然产生所需的结果。如果目标文件丢失,这怎么可能?还请解释一下目标文件的真正作用是什么?

4

6 回答 6

2

From source to executable (in a really oversimplified sort of way):

1) The pre-processor gathers the #include'd files for each .cpp in turn, runs macros, etc, and produces a "translation unit" for each file. These contain all the includes, and the macros have been evaluated: it's otherwise recognisable as source code.

2) The compiler runs over each translation unit, and turns the source into machine-instructions in "object files". These object files contain references (called "symbols") to the functions and variables it has defined, and those that are mentioned but never defined.

3) The linker grabs all the object files, and matches up the symbols across different object files. It then produces an executable.

You can freely run your executable without either the source or object files: these were read in order to produce the next step. Object files are left behind because usually you don't need to rebuild everything each time you press compile: if you only changed one source file, you only need build one new object file, and one new executable.

于 2013-05-10T15:03:56.600 回答
2

目标文件在编译时链接......然后目标文件在所有编译后都是多余的。o 文件在构建之间维护,因此您不需要重新构建应用程序的未更改部分。

于 2013-05-10T14:56:18.320 回答
1

文件在运行时.o不链接exe,它们在编译时链接到它(特别是在链接步骤期间)。一旦你有了一个可执行文件,你就可以安全地删除所有链接到它的目标文件。删除所有静态链接到的静态库也是可以的exe,因为它们的内容成为可执行文件的一部分。

于 2013-05-10T14:56:18.893 回答
1

目标文件包含编译的结果。exe 文件包含链接的结果。如果您希望exe仍然工作,您可以删除o文件

于 2013-05-10T14:56:53.397 回答
0

有两种类型的链接:静态和动态。当您编译某些东西时,编译器会生成静态链接到可执行文件中的目标文件。只有当您使用外部库并且仅当您动态链接它时,您才需要访问它。

于 2013-05-10T14:57:36.717 回答
0

.o文件用于编译,.exe. 其中.o编译后的目标代码,稍后用于编译其他程序。

其中.exe是编译后的文件,不需要.o.

给定编译:

g++ -c Hello.cpp -o Hello.o
g++ Hello.o main.cpp -o mainprogram.exe

第一行,创建一个.o文件但不做外部链接。第二行使用此文件.o并将.cpp您的程序链接在一起。

程序运行所需的唯一文件.exe.so文件,或者.a分别是共享库和静态库。

对于目标文件,这可能会有所帮助http://en.wikipedia.org/wiki/Object_file

于 2013-05-10T14:57:17.333 回答