简体   繁体   English

在 .cpp 文件中定义静态类成员时的未定义引用错误

[英]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和子目录srctest目录, src包含a.hppa.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.

相关问题 在.cpp中初始化私有静态成员给我错误:未定义的引用 - Initializing private static member in .cpp gives me error: undefined reference 在静态成员中对类静态成员的未定义引用 - Undefined Reference to class static member in static member 对类的静态成员的未定义引用 - Undefined reference to a static member of the class 未定义对 class 成员的 static 成员的引用 - Undefined reference to static member of class 未定义引用 static class 成员 - Undefined reference to static class member C ++:链接器错误:未定义的引用仅对在单独的文件中定义的一个特定的类成员 - C++: Linker error: undefined reference only to one specific class member defined in a separate file 当我在“类os”中调用自定义成员函数时,JVM 9中出现“未定义引用”的错误 - ERROR of “undefined reference” in JVM 9 when I invoke a self-defined member function in “class os” 在.cpp文件中使用类的静态成员 - using static member of a class in .cpp file 未定义对Singleton类的静态成员函数的引用 - Undefined reference to static member function of Singleton class 未定义引用静态成员函数内的静态类成员变量 - undefined reference to `Static Class Member variable inside Static member function'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM