当前位置:网站首页>Can global variables be defined in header files

Can global variables be defined in header files

2022-04-23 14:05:00 JokerYourMemory

    I met a pit today , stay VS When compiling and running multiple files on , Global variables are defined in the header file a, The header file is implemented by the class CPP And where the main function is located CPP Include and declare extern int a. However, multiple definition errors are reported when linking . I watched it on the Internet , This article gives an answer : Can you define global variables in the header file ?. In summary , There are two reasons for reporting errors CPP, Each generates its own OBJ, So when looking for symbols , You can find that there is also a variable in each other a, So it's wrong . therefore , If you can guarantee that your header file is included only once , Then you can define other linked variables in it , If there is no guarantee , To quote the author “ Then you can just find a source file , Define the global variable into the source file , Then create a new header file , It's going on inside extern  The declaration of this variable , Finally, in the source file that needs to use this global variable include Your new header file is OK 了 ”. If this method is written makefile It shouldn't be difficult , Historically common interfaces 、 Header files are put together , For this The header file of shared global variables is put here , Just write normally .

PS: The concept of definition , No addition extern Or initialization is regarded as definition . Statement only extern type-name a A kind of

版权声明
本文为[JokerYourMemory]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231401091186.html