0

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 stdafx.h. But precompiled header is shared between projects.

Recently somebody placed definition of variable inside stdafx.cpp 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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
elanius
  • 487
  • 2
  • 19
  • 1
    Typically you don't want to define a variable in *any* header. Every includer of that header will pick up the definition and the linker will then throw a fit. – user4581301 Feb 27 '17 at 20:33
  • 1
    I recommend against using precompiled headers unless building of your program takes a very long time (like minutes). IMO, your program should be structured so that only a couple of files are modified at a time. Most of the files should not be changing so there are fewer compilations; thus keeping the build time short. – Thomas Matthews Feb 27 '17 at 22:01
  • Don't share pre-compiled headers between projects unless you can guarantee that the project build settings in both projects are identical and will stay identical – Richard Critten Feb 27 '17 at 23:00

1 Answers1

2

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?

Community
  • 1
  • 1
user4581301
  • 33,082
  • 7
  • 33
  • 54