Visual Studio 2019中inl文件引发的符号多重定义问题求助
Hey there! Let's break down why you're hitting that linker error and walk through how to fix it.
What's Causing the Problem?
Your setup has the constructor a::a() defined directly inside degradation.inl, which gets included into header.hpp. When multiple source files (like helpme.cpp and others in your project) #include <header.hpp>, each source file compiles its own copy of the constructor's full definition into a .obj file.
When the linker tries to combine all these .obj files into your final program, it spots duplicate definitions of the same constructor—hence the LNK2005 error.
Solutions to Resolve the Error
Here are three solid ways to fix this:
1. Mark the Function as inline
Add the inline keyword to your constructor definition in degradation.inl. This tells the compiler that multiple copies of the function across translation units are acceptable (inline functions are exempt from the one-definition rule).
Update degradation.inl like this:
inline a::a() { std::cout << "the hopless one\n"; }
Quick note: I added std:: before cout—your original code misses this, and since your header doesn't use using namespace std; (good practice for headers, by the way!), you'd hit a compile error without the namespace qualifier.
2. Move the Implementation to a Separate .cpp File
Instead of including the .inl in your header, create a dedicated source file (e.g., header.cpp) to hold the constructor definition. This ensures the function is only compiled once, eliminating duplicate definitions.
Create header.cpp with this content:
#include "header.hpp" a::a() { std::cout << "the hopless one\n"; }
Don't forget to add this .cpp file to your Visual Studio project so it gets compiled alongside your other files.
3. Restrict .inl Inclusion to One Translation Unit
If you want to keep using the .inl file, remove the #include "degradation.inl" line from header.hpp, then include the .inl file in exactly one .cpp file in your project. This guarantees the constructor is only defined once across the entire program.
Quick Side Check
Your header's include guards (#ifndef HEADER_HPP etc.) are correctly set up—they prevent duplicate inclusion of the header in a single source file, but they don't solve the multiple-definition linker issue we're fixing here.
内容的提问来源于stack exchange,提问作者Alex Porubaimikh

