compiler construction - Preprocessing vs Linking -
everywhere linker (besides relocation, seem put under "loading") people give examples of 2 (say) c modules call functions each other.
as far understand , should taken care of preprocessing (#include etc). can understand if want assemble 2 modules @ different times need link them later. when use gcc, directly outputs executable , in context don't see point of linking except when preprocessing (which recursive i'd guess) final hits object code.
note : i'm referring static linking here. can see point when comes dynamic linking.
gcc using lot of tools create executable, compiler 1 of them , linker, preprocessor etc, see it's doing pass -v
option. if want see intermediate files use -save-temps
ie once you've created files below try this...
gcc-5 -save-temps -v -std=c11 -wall -pedantic-errors main.c foo.c
if in directory you'll see several files...
a.out // executable when no name specified foo.c // original foo.c foo.h // original foo.h foo.i // preprocessed ouput of foo.c , foo.h foo.o // foo object file foo.s // foo assembler main.c // original main.c main.i // main preprocessed main.o // main object file main.s // main assembler
if in main.i
you'll notice contains this
# 1 "foo.h" 1 int foo(int i);
but doesn't know function foo does. that's in foo.i
. means when object files created main.o
knows needs foo
function. connecting symbol foo
in main.o foo
in foo.o linker doing.
here's example, create following 3 files
foo.h
#ifndef foo_h #define foo_h int foo(int i); #endif
foo.c
#include "foo.h" int foo(int i) { return - 1729; }
main.c
#include "foo.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> int main(void) { printf("%d\n", foo(1)); return 0; }
create object files ie not executable follows, note i've added verbose flags this..
gcc-5 -v -std=c11 -wall -pedantic-errors main.c foo.c -c
if had used -o
flag see actual linker command gcc called link objects executable ie
gcc-5 -v -std=c11 -wall -pedantic-errors main.c foo.c -o fooer
at point find 2 object files in directory. can create executable using ld follows (note mac specific, use output gcc -v find correct command machine).
ld -dynamic -arch x86_64 -macosx_version_min 10.11.3 -lsystem main.o foo.o -o fooer
Comments
Post a Comment