solved a problem about undefined / unresolved reference in c

来源:互联网 发布:suse linux配置ip 编辑:程序博客网 时间:2024/03/29 06:10

//test.c

extern int a;

static int f(){

    return a;

}

 

//main.c

static int a=20;
int main(){

     return 0;
}

 

There will be no problem compiling this code,in msvc. In fact f() refereced a variable a defined staticly in main,c .because there is no other functions calling f(), it won't be linked.

 

 but if add g() to test.c

 

int g(){
 return f();
}

 

then msvc and intel c++ complains ahout undefined reference, because f is called by g, and g is used externally.

if we add static defination to g,then it still works. because g is used only in test.c,and no other functions called g, so it won;t be linked too.

 

if using c++ builder compiler, it is even not a problem if g is a non static function, as long as there is no other compile unit called g. 

 

under gcc, even static functions not using by any other functions will be linked. so the above code will generate an underfined error. the only exception is that if the function is decoration by static inline. but as we know inline functions is not always being inlined. such as belows:

 

static inline int f(){

    return a;

}

int (*delegate)()=f;

 

because a function referenced by a function pointer can not be inlined, so the above code can not be linked either.