Do MFC projects cause multiple-definition linker errors?

Is there anything special about how MFC projects are handled?

Here is the script. I like to define member functions of a class in a file hinstead of breaking the 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 is just great.

If I take the doubleDef.hMFC into the dialogue project and add it #include "doubleDef.h"to the hmain dialogue file , I will get LNK2005, saying that it is funcalready defined, which seems to be #pragma onceignored.

If I instead include doubleDef.hin the main dialog file cpp, everything is in order. But on an empty Win32, I can enable it doubleDef.h"several times" by doing the following:

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;
}

, , #pragma once ( doubleDef::func()).

doubleDef , h. , func inline , ( int func() {return 4;}), h .

inline , , h inline.

?

+4
3

Win32 , , -op. , .

MFC mainfrm.h. mainfrm.cpp. , , .

1 > MainFrm.obj: LNK2005: "public: int __thiscall doubleDef:: func (void)" (? func @doubleDef @@QAEHXZ), MfcTest.obj 1 > FileView.obj: LNK2005: "public: int __thiscall doubleDef:: func (void)" (? func @doubleDef @@QAEHXZ), MfcTest.obj 1 > ClassView.obj: LNK2005: "public: int __thiscall doubleDef:: func (void)" (? func @doubleDef @@QAEHXZ), MfcTest.obj 1 > OutputWnd.obj: LNK2005: "public: int __thiscall doubleDef:: func (void)" (? func @doubleDef @@QAEHXZ), MfcTest.obj 1 > Wnd.obj: LNK2005: "public: int __thiscall doubleDef:: func (void)" (? func @doubleDef @@QAEHXZ), MfcTest.obj

. , , .

, , , , , (MFC) . , , cpp .

0

#pragma once , . , , .

inline, , , .

- () .

P.S. MFC .

+6

, :

, inline

.

, .cpp.

#pragma once . . - , , .cpp.

class N1 {
public:
    //Declaration 
    //Multiple .cpp files need to know about this class and its members
    int foo();
};

//Definition 
//should be done once. This should go to .cpp file
int N1::foo() {
    return 1;
}

In the above example, compilation works fine in multiple .cpp files. The compilation routine does not take into account several definitions. But the linker notices many definitions and complains. You must transfer the definition to a .cpp file or use functions inline.

class N2 
{
public:
    int foo(); 
};

inline int N2::foo() 
{ //valid, even if it is repeated in different files
    return 1;
}

class N3 
{
public:
    int foo() //always valid
    { 
        return 1;
    }
};
0
source

All Articles