简体   繁体   English

为什么函数定义的顺序会改变输出二进制?

[英]Why does the order of a function definition change the output binary?

Given these two C programs 鉴于这两个C程序

Function prototype and declaration 功能原型和声明
after.c after.c

#include<stdio.h>
void hi();
int main(){
  hi();
  return 0;
}
void hi(){
  puts("hello world");
}

Function definition only 仅限功能定义
before.c before.c

#include<stdio.h>
void hi(){
  puts("hello world");
}

int main(){
  hi();
  return 0;
}

compiled with: 编译:
cc -oafter after.c cc -o after.c.
cc -obefore before.c cc -obefore.c之前

md5sum * md5sum *
efac7a08389095a718b7fc9e163719ca after efac7a08389095a718b7fc9e163719ca之后
41e81298acdf96091b4a9326a4557b0c after.c 41e81298acdf96091b4a9326a4557b0c after.c
d5b87a14479e764f1c8a8669182773a1 before d5b87a14479e764f1c8a8669182773a1之前
924ec57ea6ef7ee306edfd0ec7f5fd54 before.c 924ec57ea6ef7ee306edfd0ec7f5fd54 before.c

As you can see, it will produce different binaries. 如您所见,它将生成不同的二进制文件。 Why is this so? 为什么会这样? What's so different about before and after? 之前和之后有什么不同? Is there a speed difference? 有速度差吗?

There is no requirement for the compiler/linker toolchain to produce executables with identical checksums for equivalent programs. 编译器/链接器工具链不需要为等效程序生成具有相同校验和的可执行文件。 In fact, some compilers on certain platforms would produce different executables when the same program is rebuilt twice. 实际上,当同一程序重建两次时,某些平台上的某些编译器会生成不同的可执行文件。

See, for example, exe checksum different after each recompile 例如,参见每次重新编译后不同的exe校验和

You'd have to profile to executable to see if there's any performance difference (in your example, there will almost certainly be none). 您必须分析到可执行文件以查看是否存在任何性能差异(在您的示例中,几乎肯定没有)。

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

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