在多个cpp文件上使用类/结构/联合

Using a class/struct/union over multiple cpp files C++

本文关键字:结构 联合 cpp 文件      更新时间:2023-10-16

我试图在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