在头文件和 cpp 文件中使用一次 #pragma 时出现结构重定义错误

Getting struct redefinition error while using #pragma once in header and cpp files

本文关键字:文件 #pragma 一次 结构 错误 定义 cpp      更新时间:2023-10-16

Title.我在所有相关文件中使用过一次杂注,但仍然收到此错误。我将不胜感激任何帮助。

事件.h:

//This file is relevant to the others.
#pragma once
enum QueueType {Interactive, Noninteractive};
enum EventType {Start, Core, SSD, TTY};
struct Event {
//Event info
int time;
EventType e;
int PID;
QueueType q;
};

队列.h:

#pragma once
#include "Event.h"
//Problem code
struct nodeType {
Event info;
nodeType *link;
};
//Everything else in the file is basic Queue functions. Will provide if needed.

PriorityQueue.h:

#pragma once
#include "Event.h"

struct nodeType {
Event info;
nodeType *link;
};
//Also contains Priority Queue functions

主.cpp:

#include <iostream>
#include <string>
#include <assert.h>
#include "Event.h"
#include "Queue.h"
#include "PriorityQueue.h"
using namespace std;
//Also includes some test code 

在 Queue.h 和 PriorityQueue.h 的实现文件中,我使用一次编译指示,并包含它们各自的头文件以及 iostream 和断言。我包括使用命名空间标准,因为我很懒。我所做的所有其他研究似乎都归结为不使用警卫的人,我认为这不是这里的问题。任何帮助将不胜感激。

您已经在两个不同的标头中定义了两次结构nodeType。这将导致您的错误。仅在一个标头中定义它,或者如果它们是不同的类型,请为它们指定不同的名称或将它们放在单独的namespace中。

#pragma once或包含保护只能防止特定标头的多个包含;如果您以当前的方式违反了一个定义规则,则包含保护不会拯救您。