#pragma weak

采用 #pragma weak name 形式时,指令使 name 成为弱符号。链接程序没有找到 name 的符号定义时,不会显示错误消息,也不会出现符号的多个弱定义的错误消息。链接程序仅执行第一个遇到的定义。

如果另一个编译单元有函数或变量的强定义,那么 name 将链接到它。如果没有 name 的强定义,那么链接程序符号的值为 0。

Example1

编译单元A cu1.c

#include <stdio.h>
extern int foo;
#pragma weak foo
int main() {  
	int *ptr;  
	ptr = &foo; 
	 if (ptr == 0) {    
		printf("foo has not been defined/n"); 
	 } else {    
		printf("foo was already defined as %d/n", foo);  
	}
}

编译单元B cu2.c

int foo = 1;

只编译单元A:gcc cu1.c && ./a.out ,执行if语句。

编译两个单元:gcc cu1.c cu2.c && ./a.out ,执行else语句。

Example2

cu3.c

#include <stdio.h>
extern void foo(void);
#pragma weak foo
int main() {  
	if (foo != NULL) {    
		foo();  
	} else {    
		rintf("foo has not been defined/n");  
	}
}

编译 gcc cu3.c && ./a.out ,提示foo未被定义。

Example3

编译单元A cu4.c

#include <stdio.h>
extern void foo(void);
void foo1(void) {  
	printf("Just in function foo1()/n");
}
#pragma weak foo = foo1
int main() { 
	foo();
}

编译单元B cu5.c

#include <stdio.h>void foo(void) {  printf("In function foo()/n");}

只编译单元A:gcc cu4.c && ./a.out ,执行foo1。

编译两个单元:gcc cu4.c cu5.c && ./a.out ,执行foo。




  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值