elanius elanius -3 years ago 113
C++ Question

definition of variable in stdafx.cpp

I have visual studio solution which contains various of C++ projects. For simplicity there are two projects. One for .lib and another for .exe. Both project use precompiled header

. But precompiled header is shared between projects.

Recently somebody placed definition of variable inside
and because it is shared between projects I got:
error LNK2005: "int x" (?x@@3HA) already defined in stdafx.obj

So my question is: Is it ok to put definitions into precompiled header? (in cpp part from which is precompiled header created)

I would guess that precompiled header should contain only declarations of symbols and not definitions. Or am I wrong?

Answer Source

Typically you don't want to define a variable in any header.

When a header is included, it is effectively pasted into the including file before compilation starts. This means anything defined in the header will be repeated in every file including the header. This usually compiles just fine, but leaves the linker with the problem of figuring out which definition is the real definition.

If everyone is to share a single x, place

extern int x;

in a header and

int x; 

in an appropriate cpp file.

If every includer is to have their own private x

static int x;

goes in the header, but personally I see this as an ugly dodge that you should try to work around.

As to whether it is legal to put stuff other than headers you want precompiled into in stdafx or not, I honestly don't know. Never done it. I do know that it's not how stdafx.h is intended to be used, you only want to put headers from libraries that will not be modified as part of the project in stdafx.h, so I wouldn't do it.

Recommended reading: Purpose of stdafx.h, What's the use for "stdafx.h" in Visual Studio?, and How to use stdafx.h properly?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download