GCC的weak可以用来覆盖库函数。即,将库函数的函数声明声明为weak,则自己可以定义一个一模一样但功能不同的函数,此时就会调用自定义的版本,如果没有自定义,那么就将调用库函数版本。
下面是一个小例子:
main.cpp
a.h
a.cpp
main.cpp:
#include <stdio.h>
#include <iostream>
#include "a.h"
using namespace std;
/*
void print()
{
printf("print in the main.cpp\n");
}
*/
int main()
{
print();
return 0;
}
a.h:
#ifndef _AH_
#define _AH_
#include <stdio.h>
// open or close
void print() __attribute__((weak));
#endif
a.cpp:
#include <stdio.h>
#include "a.h"
void print()
{
printf("print in the a.cpp\n");
}
chen@ubuntu:~$ g++ main.cpp a.cpp -o main
chen@ubuntu:~$ ./main
print in the a.cpp
将main.cpp中的注释去掉:
chen@ubuntu:~$ g++ main.cpp a.cpp -o main
chen@ubuntu:~$ ./main
print in the main.cpp
简言之,弱符号可以解决多个函数调用哪个的问题。将A声明为弱符号,这样,当B没有出现的时候,就会用A,当B(强符号)出现的时候,就会用B。
384

被折叠的 条评论
为什么被折叠?



