我有下面提到的类定义的以下文件:
//File1.hpp
class A{
public:
static std::map<std::pair<unsigned, unsigned>, unsigned> var1;
};
//File2.cpp
#include "File1.hpp"
static std::map<std::pair<unsigned, unsigned>, unsigned> CreatVar1() {
std::map<std::pair<unsigned, unsigned>, unsigned> var;
var[std::make_pair(0, 0)] = 0;
return var;
}
std::map<std::pair<unsigned, unsigned>, unsigned> A::var1 = CreateVar1();
void main()
{
std::pair<unsigned, unsigned> pair1;
pair1 = std::make_pair(1, 2);
std::map <std::pair<unsigned, unsigned>, unsigned > a;
a[pair1] = 3
A::var1 = a;
//It calls File3.cpp after this
}
//File3.cpp
#include "File1.hpp"
void method1()
{
std::map <std::pair <unsigned, unsigned>, unsigned> b=A::var1;
}
然而,当我这样做时,我在File3.cpp中得到以下错误.....
undefined reference to `A::var1'
有没有办法可以纠正这个错误?
我已经看过this question,但程序员忘了初始化。我已经完成了初始化;别的东西是错的。
答案 0 :(得分:2)
而不是输入:
g++ File2.cpp
g++ File3.cpp
输入:
g++ File2.cpp File3.cpp
(用你正在使用的c ++编译器替换g ++)
默认情况下,c ++编译器将尝试在命令行上编译所有源文件,然后将它们链接到一个完整的程序中。您可以通过添加-c命令行选项来抑制此行为。
答案 1 :(得分:0)
纠正了拼写错误并添加了一个缺少的分号,它现在编译并链接。
#include <map>
class A{
public:
static std::map<std::pair<unsigned, unsigned>, unsigned> var1;
};
static std::map<std::pair<unsigned, unsigned>, unsigned> CreateVar1() {
std::map<std::pair<unsigned, unsigned>, unsigned> var;
var[std::make_pair(0,0)]=0;
return var;
}
std::map<std::pair<unsigned, unsigned>, unsigned> A::var1 = CreateVar1();
int main()
{
std::pair<unsigned,unsigned> pair1;
pair1=std::make_pair(1,2);
std::map <std::pair<unsigned, unsigned>, unsigned > a;
a[pair1]=3;
A::var1 = a;
//It calls File3.cpp after this
return 0;
}
void method1()
{
std::map <std::pair <unsigned, unsigned>, unsigned> b=A::var1;
}