本文介绍了案例标签中的extern const变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 你好NG 我有以下代码: file1.h: static const int iValue = 5; < EOF> file2.cpp #include< iostream> #include" file1.h" int main(int args,char * argv []) { switch(args){ case iValue: std :: cout<< Hello \ n; } } < EOF> 这可以很好地作为常量iValue的值。 编译file2.cpp中的main() - 函数时就知道了。 我还有一些包含file1.h的cpp文件。因此我有一份 " iValue"在每个翻译单元中,因为它具有内部链接。在使用这些目标文件(翻译单元)制作的 可执行文件中,我有 该变量的几个副本;都具有相同的价值。 现在,我想改变iValue的链接。 to extern以便 只是我的可执行文件中此常量的一个符号。 当我更改关键字static时extern我有一个问题, 符号在我的可执行文件中不止一次定义。 当我只声明变量iValue时在file1.h中使用外部链接 (" extern const int iValue;")并在一个名为file1.cpp的新文件中定义 (" extern const) iValue = 5;),然后我对多个 定义没有问题,但我的函数main()中有一个新问题,因为值为 的 iValue"编译file2.cpp时不知道。 你有什么建议我如何编译我的所有代码而没有 多于一个符号 iValue"在我的程序?或者,我想要达到的是什么 ? 提前感谢您的所有答案, ChrisHello NGI have the following code:file1.h:static const int iValue = 5;<EOF>file2.cpp#include <iostream>#include "file1.h"int main(int args, char* argv[]){switch(args) {case iValue:std::cout << "Hello\n";}}<EOF>This works fine as the value of the constant "iValue" is known whencompiling the main()-function in file2.cpp.I have some more cpp-files which include file1.h. Therefore I have a copy of"iValue" in each translation unit as it has internal linkage. In theexecutable which is made with these object files (translation units) I haveseveral copies of that variable; all having the same value.Now, I would like to change the linkage of "iValue" to extern so that thereis only one symbol for this constant in my executable.When I change the keyword "static" to "extern" I have the problem that thesymbol is more than once defined in my executable.When I only declare the variable "iValue" in file1.h with external linkage("extern const int iValue;") and define it in a new file called file1.cpp("extern const iValue = 5;"), then I have no problem with multipledefinitions but I have a new problem in my function main() because the valueof "iValue" is not known when compiling file2.cpp.Do you have any suggestions how I can compile all my code without havingmore than one symbol for "iValue" in my program? Or is it not possible whatI am trying to reach?Thanks for all your answers in advance,Chris推荐答案 well。我想你应该记住,案例值只能是 常量积分值。well. I think you should keep in mind that the case value can only beconstant integral values. 你对此有何意义?不是extern const int iValue a 常数积分值?What do you exactly mean with this? Isn''t "extern const int iValue" aconstant integral value? 这个怎么样? enum {iValue = int(5)}; 马丁 - Quidquid latine scriptum est,altum videtur。How about this?enum { iValue = int(5) };Martin--Quidquid latine scriptum est, altum videtur. 这篇关于案例标签中的extern const变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-22 14:30