C/C++でmain()関数の前に文を実行するにはどうすればいいですか?

3036 ワード

C言語ではGCCを使用する場合、attributeキーワードでconstructorとdestructorを宣言できます(C言語でmain関数の開始前に関数を実行する方法)
#include   
  
__attribute((constructor)) void before_main() { printf("%s/n",__FUNCTION__); } __attribute((destructor)) void after_main() { printf("%s/n",__FUNCTION__); } int main( int argc, char ** argv ) { printf("%s/n",__FUNCTION__); return 0; } 

C++では、グローバル変数とコンストラクション関数の特性を利用して、グローバル変数のコンストラクション関数で実行します(C++言語はmain関数の実行前にコードを実行する方法)#include using namespace std; class TestClass { public: TestClass(); }; TestClass::TestClass() { cout<<"TestClass"<<endl; } TestClass Ts;// , main int main() { cout<<"main"<<endl; return 0; }
転載先:https://www.cnblogs.com/klcf0220/p/5663487.html