#define XYZ before #include precompiled header

Viewed 535

I am refactoring some existing software and I regularly see this

#define XYZ 
#include "stdafx.h"

where stdafx is the precompiled header file.

Q1. Can a knowledgeable person please confirm the following?
That (except perhaps for the file stdafx.cpp) the correct order is always

#include "stdafx.h"
#define XYZ 

My reasoning is as follows. A define before the precompiled header can't affect the precompiled header even if 'used' inside the header, since the header is precompiled. The precompiled header will have used whatever the macro XYZ was set to when the initial compilation took place.

So

#define XYZ 
#include "stdafx.h"

misleads a reader into thinking XYZ may have an influence on the contents of stdafx.h.

Q2. Whether the two are functionally equivalent and my refactoring is safe?

#include "stdafx.h"
#define XYZ 

clearly defines XYZ whereas the alternative does not so clearly define it. (Using the precompiled header might well overwrite the definition with some compilers, for all I know.) Yet defining XYZ before including the precompiled header does seem to work, as it is present so often in the code I am refactoring.

Q3. Is the behaviour defined in a standard?

If I were the compiler writer, I would reject any #define prior to inclusion of a precompiled header! My VS2019 doesn't.

1 Answers

You state:

A define before the precompiled header can't affect the precompiled header even if 'used' inside the header, since the header is precompiled.

But from the Microsoft documentation Precompiled Header Files:

[#defines] Must be the same between the compilation that created the precompiled header and the current compilation. The state of defined constants is not checked, but unpredictable results can occur if your files depend on the values of the changed constants.

Related