Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function already defined in .obj

From what I understand, this error is caused by not properly using header guards when you have multiple files including the same file. In my case, this is the include tree that's causing the error:

File A includes Z, which contains the functions I need. File B includes A, and file C includes A.

Without any #pragma once's, The program gives a bunch of variations of the same error:

blahblah.obj: error LNK2005: class some::namespace::ObjectType Object already 
    defined in dialogDlg.obj

I just was wondering, given the include tree I described, what is the proper way to get this to compile properly?

I tried using #pragma once on file Z, but that didn't work. I also tried #pragma once on file A, which also didn't work. Finally I tried it on both A and Z, also didn't work.

like image 308
xcdemon05 Avatar asked Mar 04 '13 14:03

xcdemon05


People also ask

How do I fix my lnk2005?

This error can occur if the symbol is a packaged function (created by compiling with /Gy) and it was included in more than one file, but was changed between compilations. To fix this issue, recompile all files that include the packaged function.

How do I link an OBJ file in Visual Studio?

Go to project properties then from "Property Page" select the node "C/C++" their you will get "Additional Include Directories" add the name of your object file. Keep your obj file in the directory where your source code is or you can add the directory from: Tools->Options->Projects and Solutions->VC++Directories .

What are .OBJ files Visual Studio?

Object files contain relocatable machine code that is generated from your source code. Visual Studio creates one . obj file per each . cpp file. Then depending on the project (executable, static/dynamic library) you can get relocatable or non-relocatable code.


1 Answers

It seems you are trying to define a variable in a header file. If that header file is included in several source file it will be define in each source file thereby giving you the error.

Instead declare it as extern and then define in one of your source files.

So in the header file:

extern ObjectType Object;

And in a source file:

ObjectType Object;
like image 158
Some programmer dude Avatar answered Sep 20 '22 03:09

Some programmer dude