对静态库中类变量的未定义引用

undefined reference to a class variable inside a static library

本文关键字:未定义 引用 类变量 静态      更新时间:2023-10-16

我有liblib。lib.h和lib.cpp:

#ifndef LIB_H
#define LIB_H
namespace N1 {
namespace N2 {
class C1 {
    C1();
public:
    enum DAY { MONDAY, TUESDAY, END };
    struct DAY_PAIR {
        const int index;
        const int garbage;
        DAY_PAIR(int i, int g) : index(i), garbage(g) {};
    };
    static const DAY_PAIR MONDAY_PAIR;
    static const DAY_PAIR* PAIRS[END];
    static void init();
};
}
}
#endif
#include <iostream>
#include "lib.h"
namespace N1 {
namespace N2 {
const C1::DAY_PAIR C1::MONDAY_PAIR(MONDAY, 1234);
const C1::DAY_PAIR* PAIRS[] = {&C1::MONDAY_PAIR};
void C1::init() {
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}
}
}

我试着把我的虚拟程序链接到lib.a:

#include <iostream>
#include "lib.h"
int main() {
    N1::N2::C1::init();
    std::cout << N1::N2::C1::PAIRS[N1::N2::C1::MONDAY]->index << std::endl;
    return 0;
}

和g++给了我:

/tmp/ccKKqDsT.o: In function `main':
/home/h/test/cpp/nested.cpp:7: undefined reference to `N1::N2::C1::PAIRS'
collect2: ld returned 1 exit status

如果我不创建liblib。然后尝试将所有.cpp文件编译成可执行文件。

我错过了什么吗?

您的.cpp文件const C1::DAY_PAIR* PAIRS[] = {&C1::MONDAY_PAIR};行有问题

应该是const C1::DAY_PAIR* C1::PAIRS[] = {&C1::MONDAY_PAIR};

lib.cpp中pair前缺少类名,所以:

const C1::DAY_PAIR* C1::PAIRS[] = {&C1::MONDAY_PAIR};