我如何最好地使用 #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 语句和标题守卫,并模拟了所有正在发生的事情的图表。

visual representation of my files

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...