[英]undefined reference error for static class member when it is defined in .cpp file
This question may seem similar to other "undefined reference error when accessing static class member" questions.这个问题可能看起来类似于其他“访问静态类成员时未定义的引用错误”问题。 I have explored them and what I understood is I need to define the static class member separately in a source file, so that an object is created for the static class member that holds data.
我已经探索了它们,我的理解是我需要在源文件中单独定义静态类成员,以便为保存数据的静态类成员创建一个对象。
My problem is that I am following definition rules but still get the undefined reference errors.我的问题是我遵循定义规则,但仍然得到未定义的引用错误。
problem can be reproduced using this code:可以使用以下代码重现问题:
main.cpp主程序
#include <iostream>
#include "src/a.hpp"
int main() {
std::cout << a::x;
return 0;
}
src/a.hpp源代码/a.hpp
class a {
public:
static int x;
};
src/a.cpp源代码/a.cpp
#include "a.hpp"
int a::x = 20;
I compile main.cpp
using g++ main.cpp -o main
.我使用
g++ main.cpp -o main
编译main.cpp
。 I have a test
directory that has main.cpp
and a sub directory src
, src
contains a.hpp
and a.cpp
.我有一个包含
main.cpp
和子目录src
的test
目录, src
包含a.hpp
和a.cpp
。
The error resolves if i define the static variable within the header file, but other posts suggest it should lead to linker errors.如果我在头文件中定义静态变量,错误就会解决,但其他帖子建议它应该导致链接器错误。
The problem was in the compile command I used, g++ main.cpp -o main
does not compile src/a.cpp.问题出在我使用的编译命令中,
g++ main.cpp -o main
不编译 src/a.cpp。 Compile it with g++ main.cpp src/a.cpp -o main
and it works fine.用
g++ main.cpp src/a.cpp -o main
编译它,它工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.