未指定库,但 printf 已链接到 C++程序?
我有以下代码:
#include <stdio.h>
int main()
{
printf ("hello world\n");
return 0;
}
在 Windows 7 x86 上使用 MSVC++ 10.0,我在命令行上编译它,如下所示:
cl.exe simple.cpp
这会生成 simple.exe (编译器自动调用链接器),并且可执行文件按预期显示“hello world”消息。当我查看带有depends.exe的可执行文件时,它显示kernel32.dll是唯一的依赖项。当我转储 kernel32.dll 库的内容时,没有显示 printf。
VC++ 是否采用某种优化,以便 printf 以某种方式直接包含到最终的可执行文件中?如果是,如何进行,是否在任何地方记录?
I have the following code:
#include <stdio.h>
int main()
{
printf ("hello world\n");
return 0;
}
Using MSVC++ 10.0 on Windows 7 x86, I compile it on the command line as follows:
cl.exe simple.cpp
This produces simple.exe (the compiler automatically calls the linker) and the executable displays the "hello world" message as expected. When I look into the executable w/ depends.exe, it shows kernel32.dll as the only dependency. When I dumpbin the contents of kernel32.dll library, there is no printf shown.
Does VC++ employ some sort of optimization so that printf is somehow included directly into the final executable? If so, how, and is it documented anywhere?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
MS VC 将“默认”库的名称嵌入到大多数目标文件中。除非您使用链接器的
-nodefaultlib
选项另行指定,否则该库(或这些库)将被链接。如果您单独使用它,它不会链接任何默认库。或者,您可以指定一个特定的库,例如-nodefaultlib:mylib.lib
,在这种情况下,它会链接除您在此处指定的库之外的所有默认库。要使用您的示例,如果您使用:
它将正确编译和链接。但是,如果您使用:
您将得到:
为了完整起见,您还可以使用编译器的
/Zl
开关来创建对象,而不嵌入任何库的名称。这主要是为了创建静态库,因此它们不会嵌入可能与您构建使用库的代码发生冲突的库名称。MS VC embeds the name of a "default" library into most object files. That library (or those libraries) will be linked unless you specify otherwise with the linker's
-nodefaultlib
option. If you use that by itself, it doesn't link any default libraries. Alternatively, you can specify a particular library, something like-nodefaultlib:mylib.lib
, in which case it links all the default libraries except those you specify here.To use your example, if you use:
It'll compile and link correctly. If, however, you use:
You'll get:
Just to be complete, you can also use the compiler's
/Zl
switch to create the object without embedding the name of any library. This is intended (primarily) for creating static libraries, so they won't embed the name of a library that could conflict with however you build code that uses your library.不再使用
libc.lib
。VC++ 10 上静态或动态包含 C 运行时库 (CRT) 的选项记录在 此处。您可以在项目选项中选择您需要/想要的一个。
libc.lib
is no longer used.The options for static or dynamic inclusion of C runtime library (CRT) on VC++ 10 are documented here. You can select the one you need/desire in Project Options.
printf(实际上是 fprintf 到 stdout)以及其他“标准”函数 malloc、exit 等与 libc.lib 静态链接,这就是为什么您在任何地方都看不到它作为 dll 的原因。
printf (actually fprintf to stdout), as well as other "standard" functions malloc, exit etc. are statically linked with libc.lib, that's why you don't see it as a dll anywhere.