Reputation: 133
While implementing three files (tree.h, tree.cpp, and node.h) into an existing project, I've run into "multiple definition of" errors when trying to reference them in my parser.h and parser.cpp files. I am using include guards to prevent multiple inclusion but I don't think that is doing what I want it to. I am also using plain C++99 and compiling on a Linux machine, I don't have control over that.
The getNode() is defined with the node_t struct in node.h and both need to be available to parser.cpp, parser.h, tree.cpp, and 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
Makefile I tried adding node.h and token.h to the OBJFILES but that only caused those files to be deleted when I did 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) *~
node.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
I took all my files and their #include statements and header guards and mocked up a diagram of what all is happening.
Upvotes: 0
Views: 329