Is there something special about how an MFC project handles includes?
Here's the scenario. I like to define my class member functions in the h
file, instead of splitting up a class between two files.
In Visual Studio I can create an empty Win32 project and do something like this:
main.cpp:
#include "doubleDef.h"
int main()
{
doubleDef t;
t.func();
return 0;
}
doubleDef.h:
#pragma once
class doubleDef
{
public:
int func();
};
int doubleDef::func()
{
return 4;
}
This builds just fine.
If I take doubleDef.h
into an MFC dialog project, and add #include "doubleDef.h"
to the h
file of the main dialog, I get LNK2005, saying that func
is already defined, making it seem as if the #pragma once
is being ignored.
If I instead include doubleDef.h
in the main dialog's cpp
file, everything is fine. But in the empty Win32 I can include doubleDef.h
"multiple times" by doing this:
Header.h
#pragma once
#include "doubleDef.h"
Header1.h
#pragma once
#include "doubleDef.h"
main.cpp:
#include "Header.h"
#include "Header1.h"
int main()
{
doubleDef t;
t.func();
return 0;
}
That is, it appears #pragma once
works as expected (prevents multiple definitions of doubleDef::func()
).
If I turn doubleDef
into a template class, then the function definition must be in the h
file. Likewise, I can make func
inline
, either by adding the keyword or implicitly by defining it next to the declaration in the class (as in int func() {return 4;}
), and then, again the definition must be in the h
file.
According to the documentation, the compiler treats inline
as more or less optional, so it seems like if I just want to keep everything in the h
file, I can just make everything inline
.
What gives?