solved a problem about undefined / unresolved reference in c

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值