C の __attribute__((constructor)) および __attribute__((destructor)) 構文

GCC コンパイラーを使用して C で 2 つの関数を作成します。1 つは main 関数の前に実行され、もう 1 つは main 関数の後に実行されます。 GCC 固有の構文 : 1. __attribute__((コンストラクター)) syntax : この特定の GCC 構文は、関数とともに使用すると、プログラムの起動時、つまりプログラムの前に同じ関数を実行します。 主要() 関数。 2. __attribute__((デストラクター)) syntax : この特定の GCC 構文は、関数とともに使用すると、プログラムが _exit によって終了する直前、つまり終了後に同じ関数を実行します。 主要() 関数。 説明 : コンストラクターとデストラクターの動作方法は、共有オブジェクト ファイルに、それぞれコンストラクター属性とデストラクター属性でマークされた関数への参照を含む特別なセクション (ELF の .ctors および .dtors) が含まれていることです。ライブラリがロード/アンロードされると、ダイナミック ローダー プログラムはそのようなセクションが存在するかどうかを確認し、存在する場合はそこで参照されている関数を呼び出します。これらに関して注目に値する点がいくつかあります: 1. __attribute__((コンストラクター)) 通常はプログラムの起動時に共有ライブラリがロードされるときに実行されます。 2. __attribute__((デストラクター)) 通常はプログラムの終了時に共有ライブラリがアンロードされるときに実行されます。 3. 2 つの括弧は、おそらく関数呼び出しと区別するためのものと思われます。 4. __属性__ これは GCC 固有の構文であり、関数やマクロではありません。 ドライバーコード : CPP
   // C program to demonstrate working of   // __attribute__((constructor)) and   // __attribute__((destructor))   #include      // Assigning functions to be executed before and   // after main()   void     __attribute__  ((  constructor  ))     calledFirst  ();   void     __attribute__  ((  destructor  ))     calledLast  ();   void     main  ()   {      printf  (  '  n  I am in main'  );   }   // This function is assigned to execute before   // main using __attribute__((constructor))   void     calledFirst  ()   {      printf  (  '  n  I am called first'  );   }   // This function is assigned to execute after   // main using __attribute__((destructor))   void     calledLast  ()   {      printf  (  '  n  I am called last'  );   }   
Output:
I am called first I am in main I am called last  
クイズの作成