multiple definition of 问题解决方法

问题描述:有一个opt_process.h文件,两个.cc文件都引用了这个.h文件,在.h文件中声明了一些全局变量,报错
/tmp/ccBCSKoH.o:(.bss+0x0): multiple definition of longopts'
/tmp/ccZP3F8G.o:(.bss+0x0): first defined here
/tmp/ccBCSKoH.o:(.bss+0xc0): multiple definition of
input_opts’
/tmp/ccZP3F8G.o:(.bss+0xc0): first defined here
/tmp/ccBCSKoH.o:(.bss+0x100): multiple definition of inout_opts'
/tmp/ccZP3F8G.o:(.bss+0x100): first defined here
/tmp/ccBCSKoH.o:(.bss+0x140): multiple definition of
output_opts’
/tmp/ccZP3F8G.o:(.bss+0x140): first defined here
collect2: error: ld returned 1 exit status
原因:好像是由于多次包含,然后编译.cc文件是重复 定义了。
解决方法

  1. 使用extern关键字,即变量在.c文件中声明,在.h中用extern标志即可;
  2. 用#ifndef+#define+#endif
  3. 如果全局变量是常量,使用const标志该常量(C++中),因为const常量在便宜期已经确定,无需编译,自然也没有重复定义的问题了。

1,2方法网上都有, 3方法自己实测有用,不足之处多多指教。


猜你喜欢

转载自blog.csdn.net/aaa123524457/article/details/80984049