__attribute__ ((constructor))和__attribute__ ((destructor))用法

__attribute__((constructor)) 修饰的函数在main函数之前执行 最近研究qemu,初始化的时候有类似的代码: #define module_init(function, type) \ static void __attribute__((constructor)) do_qemu_init_ ## function(void) { \ register_m 阅读详情

目录

1. 前言       

2. __attribute__介绍

3. 测试代码

4. 总结


1. 前言       

       最近看代码,有个函数根本就没被任何函数调用,但从程序运行结果来看,该函数是被调用了的,找很久都没找到哪里调用了,最后发现该函数前面用__attribute__((constructor))修饰,如下:

__attribute__((constructor)) void load_file()
{
    printf("Constructor is called.\n");
    g_count = (int *)malloc(sizeof(int));
}

2. __attribute__介绍

       __attribute__可以设置函数属性(Function Attribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)。__attribute__前后都有两个下划线,并且后面会紧跟一对原括弧,括弧里面是相应的__attribute__参数。

__attribute__语法格式为:__attribute__ ( ( attribute-list ) )  函数定义

如果函数被设定为constructor属性,则该函数会在main()函数执行之前被自动的执行;若函数被设定为destructor属性,则该函数会在main()函数执行之后或者exit()被调用后被自动的执行。

3. 测试代码

#include <stdio.h>  
__attribute__((constructor)) void load_file()
{
    printf("Constructor is called.\n");
}
 
__attribute__((constructor(100))) void load_file1()
{
    printf("Constructor 100 is called.\n");
}
 
__attribute__((constructor(102))) void load_file2()
{
    printf("Constructor 102 is called.\n");
}
 
__attribute__((constructor(99))) void load_file3()
{
    printf("Constructor 99 is called.\n");
}
 
 
__attribute__((destructor)) void unload_file()
{
    printf("destructor is called.\n");
}
  
int main(int argc, char **argv)  
{  
    printf("this is function %s\n", __func__);  
    return 0;  
}  

执行结果如下:

 

只有constructor有优先级,指定优先级时,先执行优先级小的,再执行优先级大的,最后执行没有指定优先级。0-100是保留优先级。 

       另外在升级接口时,希望用户使用新接口,而不希望用户再使用原来的旧接口,可以利用类似如下的机制提示用户,当用户在自己的项目使用旧接口时,编译器就会发出警告,提示旧接口已经废弃:

__attribute__((deprecated("该方法已废弃,不建议使用"))) void load_file4()
{

}

int main(int argc, char **argv)
{
    load_file4();
    return 0;
}

4. 总结

  • attribute((constructor)) 先于main()函数调用,attribute((destructor)) 在main()函数后调用
  • 只有constructor有优先级,指定优先级时,先执行优先级小的,再执行优先级大的,最后执行没有指定优先级。0-100是保留优先级。
  • 可以利用attribute和deprecated对不建议使用或废弃的接口进行说明。

注意:attribute((constructor)) 、attribute((destructor))功能仅仅适用于GNU的gcc编译器,在  MSVC编译器中使用会编译报错,提示不支持。

参考链接:

【1】:https://blog.csdn.net/m0_51139226/article/details/126457719

【2】:https://cloud.tencent.com/developer/article/2008172

__attribute__((constructor))和__attribute__((destructor)) gcc为函数提供了几种类型的属性,其中包含:构造函数(constructors)和析构函数(destructors)。  程序员应当使用类似下面的方式来指定这些属性: __attribute__((constructor)) // 在main函数被调用之前调用 __attribute__((destructor)) // 在main函数被调用之后调12 #include __attribu 阅读详情

相关推荐

编译链接实战(16)常见编译器内置属性修饰符

请记住,全局变量的初始化顺序是依赖于编译器和链接器的具体实现的,可能在不同的编译器和平台上有所不同。需要注意的是,初始化函数的优先级仅用于确定它们的执行顺序,并不表示初始化的速度。默认情况下,没有指定优先级的初始化函数被视为具有中等优先级(0),而通过显式设置优先级,可以控制初始化函数的执行顺序。特性为开发者提供了一种方便的方式来定义在程序启动时自动执行的初始化函数,使得全局的初始化工作变得更加简单和方便。是GCC和兼容的编译器中的一个特性,用于指示编译器将一个函数标记为在程序启动时自动执行的初始化函数。

二进制君 2522

__attribute__((constructor))用法解析

今天在看ProtocolKit的源码,看到了这么一行代码. __attribute__((constructor)) static void _pk_extension_inject_entry(void) { 主要造成疑惑的是 __attribute__((constructor)),以前看过关于__attribute__这个关键字的,大概还记得就是可以修饰类型,函数什么的.类似一个编译标记.但是具体用法忘记了. attribute GNU C 的一大特色就是__attribute__ 机制。

chenpuo的博客 1万+

GCC:__attribute__((constructor))和__attribute__((destructor))

另外还可以为__attribute__((constructor)设置优先级:__attribute__((constructor (priority)))gcc定义了自己的可以用于修饰变量,函数及类型的属性,格式为:__attribute__ ((attribute-list))__attribute__((constructor))用于修饰的函数会在main之前就被执行。__attribute__((destructor))用于修饰的函数会在mian完成之后被执行。

风静如云的博客 919

__attribute__((constructor)) 与__attribute__((destructor)) 的用法

__attribute__((constructor)) 与 __attribute__((destructor)) 是 GCC 中用来修饰函数的,constructor 可以使被修饰的函数在 main() 执行前被调用,destructor 可以使被修饰的函数在 main() 执行结束或 exit() 调用结束后被执行。 __attribute__((constructor)) void constructor_func() { // ... } __attribute__(...

stone8761的专栏 2521

Claude code-review 插件深度解析:AI 驱动的智能代码审查系统

Claude Code Review 插件深度解析:AI 驱动的智能代码审查系统 该插件通过多 Agent 并行工作方式自动审查 PR,采用置信度评分机制(80+分保留)过滤误报,确保高质量反馈。核心功能包括: 5个专业化 Agent 并行审查(规范合规性、bug检测、历史分析等) 8步工作流程:从资格检查到 GitHub 评论发布 创新性置信度评分系统(0-100分),严格过滤7类误报 结合 CLAUDE.md 规范和历史 PR 评论实现一致性审查 技术亮点: 多 Agent 架构(Haiku/Sonne

虚心若愚 2286

实战测评:4大搜索API(You.com/Tavily/Exa/Perplexity)谁更适合你的AI项目?附Python调用代码

本文实战测评了You.com、Tavily、Exa和Perplexity四大搜索API在AI项目中的集成应用,详细对比了它们的技术特性和Python调用方法。针对LLM实时数据需求,You.com的优化设计表现突出,支持32k大上下文窗口和快速响应。文章提供了完整的代码示例和场景化选型建议,帮助开发者高效集成搜索API到AI项目中。

weixin_42569329的博客 488

__attribute__((constructor))和__attribute__((destructor))的用法

最近在学习FIO源码的时候,一开始总是没能理解FIO是怎么注册ioengine,运行到main里面的时候engine_list已经插入了所有的ioengine. 后来发现原来是因为FIO在注册ioengine函数之前加上了属性:__attribute__((constructor)), 本着不懂就学的态度,立马去查阅了相关的资料。汇总如下以作记录。 首先在GNU gcc的官网文档中查看__attribute__的有关资料: 属性说明符用于描述函数,变量,类型(比如结构体,联合和枚举)标签,枚举器,语句的属性

LITTENg的博客 1117

了解随机振动疲劳分析中 Ansys nCode DesignLife 的平均应力校正

通过选择静态环境,我们可以将其结果视为疲劳计算的平均应力,如图 3 所示,因此从静态偏移载荷工况中提取的平均应力用于转移预测雨流计数中所有循环的平均值。您可以通过观看下面的教学视频获得宝贵的见解,该视频将指导您完成利用 Ansys nCode DesignLife 分析平均应力对随机振动载荷下结构的影响的过程。它基于 R 比率或平均应力水平。另一方面,平均应力校正可以帮助消除平均应力的负面影响,提高结果的保真度。Ansys nCode 提供先进的平均应力校正技术,使工程师能够考虑平均应力对疲劳寿命的影响。

jkh920184196的博客 1524

C++ 在main函数执行前先运行以及在main函数执行后运行的函数__attribute__ ((attribute-list))

@TOC用法) attribute((constructor))在main函数之前,执行一个函数,便于我们做一些准备工作 __attribute((constructor))void before() { printf(“before main\n”); } attribute((destructor))在main()函数退出或者调用了exit()之后调用 __attribute((destructor))void after() { printf(“before main\n”); } ..

SunSachin的博客 610

Android GNSS 模块分析(三)JNI 层

Android GNSS;定位服务;GPS;NMEA协议;LocationManagerService;导航;

Yang_Mao_Shan的博客 5168

基于ADPSS的直驱风电单机模型建模指南:跟网型与构网型

本文介绍了基于ADPSS平台的直驱风电单机建模方法,包含跟网型和构网型两种控制策略。模型采用模块化设计,共享风力机与桨距角控制部分,通过FORTRAN语言实现自定义建模。跟网型采用锁相环同步和矢量控制,构网型则采用虚拟同步机技术模拟同步发电机特性。详细阐述了风力机气动模型、桨距角控制算法及代码实现,为新能源并网仿真提供了实用参考。全文约150字,涵盖模型架构、数学方程和ADPSS实现要点。

huanghm88的专栏 179

__attribute__作用

__attribute__用法 attribute((constructor))在main函数之前,执行一个函数,便于我们做一些准备工作 __attribute((constructor))void before() { printf(“before main\n”); } attribute((destructor))在main()函数退出或者调用了exit()之后调用 __attribute((destructor))void after() { printf(“before main\n”); }

XiaoWhy的专栏 412

动手在 SAP BTP Cloud Foundry 开发和部署 SAP UI5 应用的前置条件 - 订阅 SAP Build Work Zone Standard Version

摘要:本文介绍了SAP BTP Cloud Foundry环境中HTML5应用的概念,区分了web应用、HTML5应用和SAP UI5应用的关系。重点说明了在Cloud Foundry环境部署HTML5应用的方法是通过订阅SAP Build Work Zone standard edition服务,并详细描述了订阅过程中可能遇到的"OIDC trust missing"错误。该错误是由于业务用户认证需要配置SAP Cloud Identity Services的OpenID Connec

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 317

__attribute__机制

__attribute__机制

415

FPGA 学习笔记:Vivado 2020.2 MicroBlaze MIG 测试 DDR3 篇四

FPGA 学习笔记:Vivado 2020.2 MicroBlaze MIG 测试 DDR3 篇四

坚韧与专注 2164

【AUTOSAR-Nm】-2.2-通过CAN/Lin...信号报告Nm状态机的跳转

如何通过Can/Lin/Fr/Udp/J1939信号,获取每个通道对应状态机的跳转信息:“前一次状态”和“当前状态”。

「汽车电子助手」的博客 2467

【C语言】__attribute__((constructor)) 和 __attribute__((destructor))详细解析

标记的函数在main()函数之前执行,适合用于程序初始化。可以通过设置优先级,控制多个初始化函数的执行顺序,优先级数值越小,函数执行得越早。:标记的函数在main()函数之后、程序终止时执行,适合用于清理资源。同样可以通过设置优先级,控制多个清理函数的执行顺序,优先级数值越小,函数执行得越早。

W__winter的博客 2426

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

C/C++编程:__attribute__((constructor))、 __attribute__((destructor))

attribute((constructor)) 先于main()函数调用 attribute((destructor)) 在main()函数后调用 #include <stdio.h> #include <stdlib.h> static void before(void) __attribute__((constructor)); static void after(void) __attribute__((destructor)); static void before()

OceanStar的博客 6180

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

__attribute__(constructor)和__attribute__(destructor)

1、前言 最近看代码,看到一个函数前面用__attribute__((constructor))修饰,搜了整个程序,没发现哪个地方调用这个函数。如下: __attribute__((constructor)) void load_file() { printf(&quot;Constructor is called.\n&quot;); g_count = (int *)malloc(sizeof(i...

sun172270102的博客 7905

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

__attribute__((constructor))

__attribute__((constructor)) 先于main()函数调用 __attribute__((destructor)) 在main()函数后调用 #include <stdio.h> #include <stdlib.h> static void before(void) __attribute__((constructor)); sta...

accumla的博客 4210

函数属性__attribute__((constructor))和__attribute__((destructor))

函数声明如下:     static void breforemain(void) __attribute__ ((constructor));//在main()函数之前被执行     static void aftermain(void) __attribute__ ((destructor));//在main()退出时执行 例子如下: #include //函数属性声明

陈嘉怡的专栏 4198

gcc下__attribute__ ((constructor))和__attribute__ ((destructor))的使用

__attribute__ ((constructor))指定的函数在共享库loading的时候调用,__attribute__ ((destructor))在共享库unloading的时候调用。1. 编写源码文件ktest.c如下.    #include __attribute__ ((constructor)) static void ktest_init(void); __attribute__ ((destructor)) static void ktest_deinit(void); v

晴空's Blog 5413

GCC __attribute__((constructor)|(destructor))

在阅读TGTD的代码时发现了一个非常诡异的问题,声明了一个空的全局数组,在使用的时候却发现数组非空,在main()入口时数组已经非空.数组时在什么地方被赋值了呢?最后发现__attribute__这个东东在起作用,类似于全局变量类的构造函数在main()前被调用. __attribute__((constructor)) __attribute__((destructor)) /* te

polisan's World 1万+

GCC的__attribute__ ((constructor))和__attribute__ ((destructor))

gcc允许为函数设置__attribute__ ((constructor))和__attribute__ ((destructor))两种属性,顾名思义,就是将被修饰的函数作为构造函数或析构函数。程序员可以通过类似下面的方式为函数设置这些属性: void funcBeforeMain() __attribute__ ((constructor)); void funcAfterMain() __attribute__ ((destructor)); 带有(constructor)属性的函数将在main

落尘纷扰的专栏 6190
上一篇: C++中模板定义与声明为什么必须放在同一个文件中
下一篇: 将vsCode 打开的多个文件分行(栏)排列,实现全部显示,便于切换文件
荆楚闲人
博客等级 码龄20年 3万+粉丝 472原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值