'Visual Studio error LNK2005, confusing linking error that's caused by forcing .obj to be recompiled
I've been desperately trying to get C++ code to work in Visual Studio (versions 2017 and 2022), and I keep running into error LNK2005. My code doesn't seem to show the kind of issues that would cause error LNK2005, I think.
For example:
in main.cpp
#include <iostream>
#include "utils.cpp"
int main() {
LOG("Last time of compilation:"); LOG(__TIME__);
KEEP_CONSOLE_OPEN();
return 0;
}
and a file utils.cpp
#ifndef GC_UTILS
#define GC_UTILS
#include <iostream>
#define LOG(msg) std::cout<<(msg)<<"\n"
#define KEEP_CONSOLE_OPEN() system("pause");
#endif
This compiles fine, but the problems arise when the files are modified:
- When something in
utils.cppis modified, and I click run, it runs but the program is the same as before the changes (which can be seen from the TIME macro) - BUT if I modify anything in main.cpp, even insignificant, then the compiler will throw the error LNK2005, I assume because it's forced to regenerate main.obj
The code above compiles fine,
- when I add
int a = 6;inutils.cpp, the compiled program is the same as before the changes - when main is modified (eg changing the text "Last time of compilation" to "this won't compile"), LNK2005 and LNK1169 are thrown:
Error LNK2005 "int a" (?a@@3HA) already defined in main.obj
LNK1169 one or more multiply defined symbols found
I've tried some things:
- combinations of
#pragma onceand#ifndefguards - cleaning and rebuilding the project
- changing the version of C++
- reinstalling the IDE, changing IDE (CLion had similar issues)
Does it have to do with the macros, the IDE, my machine or what? I'm so confused, I've tried for days and days now, I will be eternally grateful for any help. I wouldn't be surprised if I'm just being stupid.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
