在多个cpp文件上使用类/结构/联合
Using a class/struct/union over multiple cpp files C++
我试图在c++中创建一个类,并能够在多个c++文件中访问该类的元素。我已经尝试了超过7种可能的情况来解决错误,但没有成功。我已经研究了类前向声明,这似乎不是答案(我可能错了)。
//resources.h
class Jam{
public:
int age;
}jam;
//functions.cpp
#include "resources.h"
void printme(){
std::cout << jam.age;
}
//main.cpp
#include "resources.h"
int main(){
printme();
std::cout << jam.age;
}
Error 1 error LNK2005: "class Jam jam" (?jam@@3VJam@@A) already defined in stdafx.obj
Error 2 error LNK1169: one or more multiply defined symbols found
我理解错误是一个多重定义,因为我在两个CPP文件中包括resources.h
。我该如何解决这个问题?我尝试在CPP文件中声明class Jam
,然后为需要访问该类的每个CPP文件声明extern class Jam jam;
。我也尝试过声明类的指针,但我没有成功。谢谢你!
您正在声明结构Jam
和,并创建该类型的名为jam
的变量。链接器抱怨说,您有两个(或更多)名为jam
的东西,因为您的头文件导致每个.cpp
文件声明自己的一个。
要解决这个问题,将您的头声明更改为:
class Jam{
public:
int age;
};
extern Jam jam;
然后将以下行放在一个的.cpp
源:
Jam jam;
您需要将定义与声明分开。用途:
//resources.h
class Jam{
public:
int age;
};
// Declare but don't define jam
extern Jam jam;
//resources.cpp
// Define jam here; linker will link references to this definition:
Jam jam;
变量jam
是在H文件中定义的,并且包含在多个CPP类中,这是一个问题。
变量不应该在H文件中声明,以避免这种情况的发生。将类定义保留在H文件中,但在一个CPP文件中定义变量(如果需要全局访问它-在所有其他文件中将其定义为extern
)。
//resources.h
class Jam{
public:
int age;
};
extern Jam jam; // all the files that include this header will know about it
//functions.cpp
#include "resources.h"
Jam jam; // the linker will link all the references to jam to this one
void printme(){
std::cout << jam.age;
}
//main.cpp
#include "resources.h"
int main(){
printme();
std::cout << jam.age;
}
作为第一步,您应该将类的定义和实例的声明分开。然后在resources.h中使用extern,并在CPP中声明实例。
:
//resources.h
class Jam{
public:
int age;
};
extern Jam jam;
//functions.cpp
#include "resources.h"
void printme(){
std::cout << jam.age;
}
//main.cpp
#include "resources.h"
Jam jam;
int main(){
printme();
std::cout << jam.age;
}
使用pragma once指令或一些定义来确保一个头文件不会在你的代码中被包含多次。
使用pragma指令的例子(Example .h):
#pragma once
// Everything below the pragma once directive will only be parsed once
class Jam { ... } jam;
使用定义(Example .h)的示例:
#ifndef _EXAMPLE_H
#define _EXAMPLE_H
// This define makes sure this code only gets parsed once
class Jam { ... } jam;
#endif
- 如何将结构/联合数组的成员传递到函数中
- 错误 C2228 左侧'.setDay'必须具有类/结构/联合
- 在C++中为结构(联合)创建构造函数
- '.expression'左边必须有类/结构/联合
- C++错误 C2227:'->looseHealth'左侧必须指向类/结构/联合/泛型类型
- C 结构/联合到C#结构
- C++ 使用比较 - '.compare'左侧必须具有类/结构/联合
- 表达式必须具有类类型,'.x'左侧必须具有类/结构/联合
- 错误c++visual studio c2227左侧'->;Init';必须指向类/结构/联合/泛型类型
- .BEGIN的左侧必须具有类/结构/联合
- 我的测试用例错误类/结构/联合
- C++ 异常情况下的错误 C2228(".val"的左侧必须具有类/结构/联合)
- 错误 C2228:".x"的左侧必须具有类/结构/联合
- 错误:C2228:左侧必须具有类/结构/联合
- 错误 C2228:".printStats"的左侧必须具有类/结构/联合
- '.getDrinkPrice'左边必须有类/结构/联合
- 通过反射在XML中的C/C++头文件中定义的可视化嵌套结构/联合
- 错误 C228:"必须多次具有类/结构/联合"的左侧
- 正在分析XML中C/C++头文件中定义的嵌套结构/联合
- 错误 C2228:'.Alloc'左侧必须具有类/结构/联合