Search code examples
c++visual-c++linker-errorsinline

"error LNK2005: already defined in .obj" for inline definition


I'm on Microsoft Visual Studio Professional 2017 Version 15.6.6. I created a Visual C++ Empty Project and added the following:

Foo.h:

#pragma once
struct Foo
{
    static Foo F1;
};
inline Foo Foo::F1;

Bar.cpp:

#include "Foo.h"

Baz.cpp: (from https://stackoverflow.com/a/65078857/1715765)

#include <sdkDdkVer.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#pragma runtime_checks("", off)
#pragma comment(linker, "/nodefaultlib /subsystem:windows /ENTRY:test")
int __stdcall test(void) { ExitProcess(0); }

#include "Foo.h"

I get the following when compiling. It compiles fine if I remove one #include "Foo.h"

Baz.obj : error LNK2005: "public: static struct Foo Foo::F1" (?F1@Foo@@2U1@A) already defined in Bar.obj

Why doesn't it work?


Solution

  • Looks like a compiler bug or non-conformance to me.

    If I ignore all of the Windows/MSVC-specific stuff in the example, then that's a valid standard C++ program (except for missing main).