• Announcements

Archived

This topic is now archived and is closed to further replies.

Compile errors: already defined in main.obj

Recommended Posts

Right, i''ll get straight to it... This struct is declared in a header file.
struct Token
{
char*	str;
TokenID	id;
}validTokens[] =
{
// base commands

{"GO",		GO		} ,

// ..and so on...


Later i use the array validTokens in various places. It can''t be a global (preferably not..) because it has to be secured in the parser class. Tokenizer.obj : error LNK2005: "struct Token * validTokens" (?validTokens@@3PAUToken@@A) already defined in main.obj Action.obj : error LNK2005: "struct Token * validTokens" (?validTokens@@3PAUToken@@A) already defined in main.obj Now when trying to build it i get these error messages, and i can''t figure out how to come around this. All header files has file guards, and i''ve made a complete "build-from-scratch", problem is still there... Any thoughts is appreciated. Now, i should inform you that this is homework, though i thought i''d ask anyway. The parser isn''t important for the school. The final product, the text game and usage of classes, is...

Share on other sites
The problem is that you''re declaring a global variable in a header (validTokens[]). You should have only the ''struct {...};'' part in that header and declare the variable in the declaration of the class you''re going to use it in. Or, to go a little easier way, declare it in the class source file (iirc, declaring it as static will make it local for the source file).

Uh, for some reason I couldn''t figure out how to write that clearly..

Share on other sites
Declare the variable as extern with no initialisation. The in one of your source files you declare the variable without extern.

I don''t think you''ll init the array when you declare the array in the header but you should be able to in the .cpp file - just make sure you specifiy enough space in the array to hold all the options.

Share on other sites
Thanks for the replies!

I used extern and it seems to work..

Share on other sites
The correct solution has already been posted, but just to clarify:

The problem presumably stems from the fact that you include the header in several compilation units, which are compiled separately and later linked together. Separate compilation means that the various compilation units have no knowledge of each other, so every compilation unit that includes the header file will create their own copy of the variable.

Declaring the variable as extern in a header is essentially an assurance that "There is a variable such as this, but it is declared externally", so that each compilation unit will merely use some sort of symbolic reference (until link time) except for the one that actually defines it. It is then the linker''s job to figure it out.

• Forum Statistics

• Total Topics
627719
• Total Posts
2978796

• 10
• 9
• 21
• 14
• 12