如何解决我如何最好地使用 #include 来防止我的多重定义错误?
在现有项目中实现三个文件(tree.h、tree.cpp 和 node.h)时,当我尝试在我的 parser.h 和解析器中引用它们时遇到了“多重定义”错误。 cpp 文件。我正在使用包含守卫来防止多重包含,但我认为这不是我想要的。我也在使用普通的 C++99 并在 Linux 机器上编译,我无法控制。
getNode() 是用 node.h 中的 node_t 结构定义的,并且两者都需要对 解析器可用。 cpp、parser.h、tree.cpp 和 tree.h。
[user]$ make
g++ -g -Wall -Wno-unused-variable -o frontend main.o scanner.o parser.o tree.o
scanner.o: In function `getNode(std::string)':
/home/user/Compilers/P2/node.h:21: multiple deFinition of `getNode(std::string)'
main.o:/home/user/Compilers/P2/node.h:21: first defined here
parser.o: In function `getNode(std::string)':
/home/user/Compilers/P2/node.h:21: multiple deFinition of `getNode(std::string)'
main.o:/home/user/Compilers/P2/node.h:21: first defined here
tree.o: In function `getNode(std::string)':
/home/user/Compilers/P2/node.h:21: multiple deFinition of `getNode(std::string)'
main.o:/home/user/Compilers/P2/node.h:21: first defined here
collect2: error: ld returned 1 exit status
make: *** [frontend] Error 1
生成文件 我尝试将 node.h 和 token.h 添加到 OBJFILES 中,但这只会在我执行 make clean
时导致这些文件被删除CC = g++
CFLAGS = -g -Wall -Wno-unused-variable
CXXFLAGS = -g
OBJFILES = main.o scanner.o parser.o tree.o
TARGET = frontend
all: $(TARGET)
$(TARGET): $(OBJFILES)
$(CC) $(CFLAGS) -o $(TARGET) $(OBJFILES)
.PHONY: clean
clean:
rm -f $(OBJFILES) $(TARGET) *~
节点.h
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "token.h"
#ifndef NODE_H_
#define NODE_H_
struct node_t
{
std::string label;
Token* token1;
Token* token2;
//struct node_t *left;
//struct node_t *right;
struct node_t *child;
};
node_t* getNode( std::string functionName )
{
// Create the node
node_t* node = (struct node_t*)malloc(sizeof(struct node_t));
node->label = functionName;
node->child = NULL;
node->token1 = NULL;
node->token2 = NULL;
return node;
}
#endif
我拿走了我所有的文件和他们的#include 语句和标题守卫,并模拟了所有正在发生的事情的图表。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。