0
点赞
收藏
分享

微信扫一扫

__attribute__修饰使用在linux编程中的使用

紫荆峰 2022-11-25 阅读 75

int __attribute__((weak)) func();

当我们用__attribute__((weak))修饰func()函数后,func就是一个弱符号。不管外部是否定义了func()我们都可以链接通过,当外部定义了就调用外部的func函数,当外部没有定义时就调用本模块的func函数。但实际上本模块并没有定义func函数,所以在调用时我们判断一下函数指针是否为空,以免造成段错误。

案例:

main.cpp

#include <iostream>

int __attribute__((weak)) add(int a, int b)
{
printf("weak add called\n");
return 0;
};

using namespace std;
int main()
{
int a = add(1, 2);
printf("weak result:%d\n", a);
return 0;
}

strong.cpp

#include <stdio.h>
int add(int a, int b)
{
printf("strong add called\n");
return a + b;
}

1.只编译main.cpp,编译成功。main中调用的是 weak修饰的add

2.编译main.cpp和strong.cpp, 编译成功。main中调用的是strong.cpp中的add


static void Create(void) __attribute__((constructor))

__attribute__((constructor))修饰函数是在main函数之前执行的函数。

static void Destory(void) __attribute__((destructor));

__attribute__((constructor))修饰函数是在main函数之后执行的函数。

案例:

main.cpp

#include <iostream>

#define MODULE_CONSTRUCTOR(void) static void Create(void) __attribute__((constructor)); static void Create(void)

#define MODULE_DESTRUCTOR(void) static void Destory(void) __attribute__((destructor)); static void Destory(void)

MODULE_CONSTRUCTOR(void)
{
printf("constructor called\n");
}

MODULE_DESTRUCTOR(void)
{
printf("destructor called\n");
}

using namespace std;
int main()
{
printf("main called\n");
return 0;
}

下面调用顺序:左中右,可以看出constructor和destructor的调用时机

__attribute__修饰使用在linux编程中的使用___attribute__

举报

相关推荐

0 条评论