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

时间:2014-08-16 08:25:47

标签: 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文件编译成可执行文件。它汇编得很好。

我错过了什么吗?

提前致谢。

2 个答案:

答案 0 :(得分:3)

您的.cpp文件在第const C1::DAY_PAIR* PAIRS[] = {&C1::MONDAY_PAIR};

时出现问题

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

答案 1 :(得分:2)

在lib.cpp中PAIRS之前缺少类名,所以:

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