Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

const [identifier] already defined in [file].obj ...

Status
Not open for further replies.

EvilCabal

Programmer
Jul 11, 2002
206
CA
Hello,

I have a .h file witch define some char* array (char ** if you prefer) and when I compile, the linker give me an 'already defined error'...

Here is the file structure :

#ifndef file.h
#define file.h

const char* myArray[] = {...

#endif

here is the exact error message : 3papbda

File.obj "cont char * * myArray" (?myArray@@#PAPBDA) already defined in main.obj

thanx for the help!
 
1. You can't use file.h in #ifndef or #define: it's not an identifier (well, it was misprint;).
2. You must understand a difference between a declaration and a definition. You may write some (compatible) declarations for your variables in your program modules (source files), but only one definition. A declaration with initialization is a definition. So you must write in .h file:
Code:
extern const char* myArray[]; // it's a declaration...
In one (any) module (not a header) you must write the definition of the myArray:
Code:
const char* myArray[] = { ... }; // it's a definition...
 
Sorry, I made a typing mistake in my last post

I meant
#ifndef FILE_H
#define FILE_H

not file.h of course. :)

I did not know you could not initialize a variable in a header. I did this many times and it always worked until now.

So I was wondering, I often declare integer constants in my header files. Is this a bad practice? Should I use the extern keyword and initialise them in the related .cpp file?

If yes, why is that?

 
You can initialize a variable in a header. It's just not a good idea. If two or more source files include the header, you will get the "already defined" error that you mentioned in the original post.
 
teriviret:
But if he's using the appropriate #ifndef directives around his header, shouldn't that prevent it from being included more than once?

ArkM:
I understand about using extern "C" for C++ functions that will be called from other languages, but I've always been a little confused about when I NEED to use just extern by itself? I've never had to use it so far.
I found this in the MSDN: "Declarations of variables and functions at file scope are external by default." Does this mean that extern is not needed for global variables or functions as the ones in EvilCabal's code?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top