...

View Full Version : c++ linking help needed, build errors



hotbeard
11-18-2004, 05:31 AM
Okay, hopefully this is an easy fix. I have three c++ files I am trying to build in MS Visual C++ .NET

BinaryHeap.h
BinaryHeap.cpp
Huffman.cpp

Huffman.cpp conatins my main() function.
It also has an #include "BinaryHeap.h"



BinaryHeap.cpp also has an #include "Binaryheap.h"

my BinaryHeap.h file has two things i need to make global. They are listed below:

struct HuffmanNode
{
string data ;
int frequency ;
HuffmanNode *left ;
HuffmanNode *right ;

};

HuffmanNode *forest[27] ;


I am getting the linking errors listed below:

binaryheap.obj : error LNK2005: "struct HuffmanNode * * forest" (?forest@@3PAPAUHuffmanNode@@A) already defined in Huffman.obj

Debug/Homework6.exe : fatal error LNK1169: one or more multiply defined symbols found


I believe the compiler is complaining that the struct is defined twice becuase of the way I have my #include's arranged. I have tried to fix this but cannot. I have no clue how to tweak the compiler settings to fix this. Can someone clue me in on how to fix this and how best to use #include statements. Thanks

Aaron

shmoove
11-18-2004, 09:32 AM
I think you are falling prey to the multiple inclusion syndrome. What you have to do to fix this is to use the preprocessor. In BinaryHeap.h, add this:


#ifndef BINARY_HEAP_H
#define BINARY_HEAP_H

// your code goes here

#endif

This way the the whole code will be omitted if the file has already been parsed.

shmoove

hotbeard
11-18-2004, 10:12 PM
Yes, I do have that code in each of my include files, yet I still get the same error.

Is it possible I don't have some compiler setting correct?

I have no clue how to set up the compiler, but I have never had this problem before.

I am only running into this problem becuase this is the first time I've ever tried to use global variables.

aman
11-19-2004, 12:53 AM
You can't declare global variables in a header like that or you will always get multiply defined symbols found errors.

Move your global variable declaration into one of your .cpp files, then use the extern keyword in the rest of your files. You can either place it in each .cpp file that you want access to it, or you can place it in the header file.

Put this in your Huffman.cpp file:

HuffmanNode *forest[27] ;


Now in your BinaryHeap.h file, put this:

struct HuffmanNode
{
string data ;
int frequency ;
HuffmanNode *left ;
HuffmanNode *right ;

};

extern HuffmanNode *forest[27] ;



Now you can access the global variable forest from any file that includes BinaryHeap.h without getting the multiple definition error.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum