问题
I'm stuck in a linker error and need some help. I'm using MSVC.
At the beginning, I made this:
/* graphics_app.h */
#ifndef DK_GRAPHICS_APP_H
#define DK_GRAPHICS_APP_H
...
class GraphicsApp {
private:
static GraphicsApp* self;
...
};
GraphicsApp* GraphicsApp::self = nullptr;
#endif /* DK_GRAPHICS_APP_H */
This header used to work... and I made some improvements, but nothing about that static member changed.
but unexpectedly I got this linker error message:
LNK2005 "private: static class GraphicsApp * GraphicsApp::self" (?self@GraphicsApp@@0PEAV1@EA) already defined in main.obj.
LNK1169 one or more multiply defined symbols found.
So, I separated this header into .h and .cpp:
/* graphics_app.cpp */
#include "graphics_app.h"
...
GraphicsApp* GraphicsApp::self = nullptr;
but I got another error:
LNK2001 "private: static class GraphicsApp * GraphicsApp::self" (?self@GraphicsApp@@0PEAV1@EA) unresolved external symbol.
LNK1120 1 unresolved externals.
Why these weird behavior happens & how can I fix?
EDIT:
I made test version to make problem simper.
This thing happens when I use my custom include directory...
such as
#include <dk/graphics_app.h>
instead of
#include "graphics_app.h"
So.. a new problem is, how can I fix this whilst using my custom include directory?
Edit2:
To make Thing much simpler..
回答1:
LNK2005: This error happened because, the header file was included in two other cpp files (compiled to obj files) . Then when the linker tried to link the obj it found two of the same definitions. But "there can be only one"!
Because of this ambiguity the linker gives up.
LNK2001: This error happened because the linker did not find the defined variable in any obj file. So I think that the new cpp is missing from your project definition.
回答2:
This header used to work... and I made some improvements, but nothing about that static member changed.
Your header is written incorrectly: you are not supposed to put definitions of entities with external linkage into header files. It could "work" as long as you included your header file into one and only one translation unit. But once you include it into two or more different translation units, you get the "multiple definition" error. Which is exactly what happened in your case.
So, I separated this header into .h and .cpp
This is the right thing to do. Now you have to make sure your graphics_app.cpp is compiled (and linked) as part of your program. This is something you forgot to do. The compiler/linker/build system cannot somehow "magically" realize by itself that your freshly created graphics_app.cpp is supposed to be part of your project.
来源:https://stackoverflow.com/questions/48465140/c-linker-strange-behavior-static-member-variable