当前位置:网站首页>全局变量能否放在头文件中定义
全局变量能否放在头文件中定义
2022-04-23 14:01:00 【JokerYourMemory】
今天遇到一个坑,在VS上进行多文件的编译运行的时候,在头文件中定义了全局变量a,该头文件被类的实现CPP和主函数所在的CPP包含且声明extern int a。但是在链接的时候报多重定义的错误。网上看了下,这篇文章给出了一个答案:能不能在头文件中定义全局变量?。总结起来就是,报错的原因就是有两个CPP,各自生成自己的OBJ,那么在查找符号的时候,都能发现对方那里也有一个变量a,那么就报错了。所以,如果你能保证你的头文件只被包含一次,那么可以在其中定义此外链接性的变量,如果无法保证的话,引用作者的话“那么你就任找一个源文件,把这个全局变量定义到这个源文件中,然后新建一个头文件,在里面进行extern 这个变量的声明,最后在需要使用这个全局变量的源文件中include你新建的头文件就OK了”。这种方法如果写起来makefile应该也不难,历来公共的接口、头文件都是放在一起,此用于共享全局变量的头文件放在这里,正常写就好了。
PS:定义的概念,不加extern或者进行了初始化都视为定义。声明只有extern type-name a一种
版权声明
本文为[JokerYourMemory]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_38084180/article/details/80500765
边栏推荐
猜你喜欢
程序编译调试学习记录
分库分表 & ShardingSphere
【项目】小帽外卖(八)
Neuron and neural network
cnpm的诡异bug
蓝绿发布、滚动发布、灰度发布,有什么区别?
Business case | how to promote the activity of sports and health app users? It is enough to do these points well
33 million IOPs, 39 microsecond delay, carbon footprint certification, who is serious?
Jenkins construction and use
Reading notes: meta matrix factorization for federated rating predictions
随机推荐
China creates vast research infrastructure to support ambitious climate goals
Program compilation and debugging learning record
对List集合进行分页
Android 面试主题集合整理
Programming travel function
生成随机高质量符合高斯分布的随机数
Express ② (routing)
Android interview theme collection
linux MySQL数据定时dump
专题测试05·二重积分【李艳芳全程班】
Ptorch classical convolutional neural network lenet
freeCodeCamp----arithmetic_ Arranger exercise
scikit-learn構建模型的萬能模板
蓝绿发布、滚动发布、灰度发布,有什么区别?
Reading notes: Secure federated matrix factorization
[code analysis (2)] communication efficient learning of deep networks from decentralized data
JS 力扣刷题 103. 二叉树的锯齿形层序遍历
大专的我,闭关苦学 56 天,含泪拿下阿里 offer,五轮面试,六个小时灵魂拷问
[VMware] address of VMware Tools
Question bank and answer analysis of the 2022 simulated examination of the latest eight members of Jiangxi construction (quality control)