c - using a method from another file without including it -
this question has answer here:
i have 2 .c files compile on makefile.
foo.c:
void foo() { printf("this foo"); }
main.c:
#include <stdio.h> int main() { printf("this main\n"); foo(); }
the makefile looks that:
all: main.o foo.o gcc -o prog foo.o main.o main.o: main.c gcc -c main.c foo.o: foo.c gcc -c foo.c
so question is: how can foo.c use printf() without me including stdio.h , how can main.c use method foo() without me including foo.c.
my guess/research makefile works linker. dont have prove , want understand how works excactly.
correct me if misunderstood something.
in compilation phase, compiler checks function calls against prototypes. function lacks prototype assumed return int
, accept number of arguments.
if turn warning level, gcc warn if prototype missing. should add -wall
, add -pedantic
diagnostics on additional things compiler think suspicious.
if compilation step succeeds, compiler creates object file contains compiled code , 2 reference tables. first table export table. contains names of functions , variables exported object file. second table import table. contains list of functions , variables referenced, declaration missing.
in case have:
foo.o:
export:
foo
import:
printf
main.o
export:
main
import:
printf foo
in linker phase, linker take list of imports , exports , match them. in addition object files , libraries specify on command line, linker automatically link libc, contains functions defined c language.
Comments
Post a Comment