4

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?

P.P
  • 117,907
  • 20
  • 175
  • 238
user1461607
  • 2,416
  • 1
  • 25
  • 23
  • 1
    Linked addresses change?? I won't suppose one version should be faster than the other. – πάντα ῥεῖ May 10 '14 at 12:17
  • "Which is faster?" just means "I haven't bothered profiling my own code". So don't ask that ;-) I'd recomend doing a little research on the ELF binary format (or whatever binary format your system uses), which will give you some insight into what the binary needs to contain. – Rook May 10 '14 at 12:21
  • I think in the output assembly of the first program, main will lie before the function, and in the last one's output, the function `hi` is before `main` – phuclv May 10 '14 at 13:08

1 Answers1

4

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).

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • _'when the same program is rebuilt twice.'_ This could especially happen for systems that put some additional information in a so called _manifest_, including compilation date/time, buildnumber, etc. – πάντα ῥεῖ May 10 '14 at 12:34
  • but the two programs are almost identical, there are no changes except for the order of it – user1461607 May 10 '14 at 12:37
  • 1
    @user1461607 Simply spoken, the order of the functions in the binary matches the order of the functions in the code. (That's not an universal truth, but it is one way the compiler might work.) If this is the case on your system, you have the reason why things are different. – glglgl May 10 '14 at 12:40