简体   繁体   中英

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

Given these two C programs

Function prototype and declaration
after.c

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

Function definition only
before.c

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

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

compiled with:
cc -oafter after.c
cc -obefore before.c

md5sum *
efac7a08389095a718b7fc9e163719ca after
41e81298acdf96091b4a9326a4557b0c after.c
d5b87a14479e764f1c8a8669182773a1 before
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

You'd have to profile to executable to see if there's any performance difference (in your example, there will almost certainly be none).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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