c++ - 对静态库中类变量的 undefined reference

标签 c++ linux g++

我有 liblib.a,它有 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;
}
}
}

然后我尝试将我的虚拟程序链接到 liblib.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.a 然后尝试将所有 .cpp 文件编译成可执行文件。它编译得很好。

我错过了什么吗?

提前致谢。

最佳答案

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

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

关于c++ - 对静态库中类变量的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25338328/

相关文章:

python - python的测试工具

c++ - 有没有办法告诉 g++ 编译器,不要在某个 -I 路径中查找包含 header ?

c++ - 什么是 std::__scan_keyword?

C++ 对象相等

c++ - C++ 中的别名和引用是一回事吗?

linux - 在 bash 中编辑一个字符的 ASCII 值

c++ - g++4.8 处理 vector future 的问题

c++ - 使用 opencv 的 H264 视频编解码器

c++ - 在大型 C++ 代码库中避免空指针异常

linux - Chrome Linux --kiosk 打印