Ans*_* PP 2 c++ definition include-guards
我在编译时遇到问题:Multiple definitions of "myFunction()"
我将在这里大大简化问题。基本上,我有 3 个文件:“main”、“header”和“myLibrary”。
#include "header.hpp"
int main() { }
Run Code Online (Sandbox Code Playgroud)
#ifndef HEADER_HPP
#define HEADER_HPP
#include "myLibrary.hpp"
// ...
#endif
Run Code Online (Sandbox Code Playgroud)
#include "header.hpp"
// ...
Run Code Online (Sandbox Code Playgroud)
#ifndef LIB_HPP
#define LIB_HPP
#if defined(__unix__)
#include <dlfcn.h>
std::string myFunction() { return std::string(); }
#endif
#endif
Run Code Online (Sandbox Code Playgroud)
#include "myLibrary.hpp"
//...
Run Code Online (Sandbox Code Playgroud)
那么,为什么编译器说我有呢 Multiple definitions of "myFunction()"?
我发现的一条线索:当我获取 header.cpp 并删除显示 的行时#include "header.hpp",程序编译时没有任何抱怨。另一方面,如果我删除myFunction(从 myLibrary.hpp 中),程序也可以毫无抱怨地编译
您正在头文件中定义函数的主体。因此,包含该标头的每个翻译单元(在本例中main.cpp为 和header.cpp)最终都会得到该函数体的自己的副本。当您尝试将这些多个单元链接在一起时,您会收到“重复定义”错误。
该函数需要在hpp文件中声明,并在cpp文件中定义:
myLibrary.hpp
#ifndef LIB_HPP
#define LIB_HPP
#if defined(__unix__)
#include <dlfcn.h>
#include <string>
std::string myFunction();
#endif
#endif
Run Code Online (Sandbox Code Playgroud)
我的图书馆.cpp
#include "myLibrary.hpp"
#if defined(__unix__)
std::string myFunction()
{
return std::string();
}
#endif
//...
Run Code Online (Sandbox Code Playgroud)