[英]Multiple definitions when using #ifdef
我在编译时遇到问题: Multiple definitions of "myFunction()"
我将在这里大大简化问题。 基本上,我有 3 个文件:“main”、“header”和“myLibrary”。
#include "header.hpp"
int main() { }
#ifndef HEADER_HPP
#define HEADER_HPP
#include "myLibrary.hpp"
// ...
#endif
#include "header.hpp"
// ...
#ifndef LIB_HPP
#define LIB_HPP
#if defined(__unix__)
#include <dlfcn.h>
std::string myFunction() { return std::string(); }
#endif
#endif
#include "myLibrary.hpp"
//...
那么,为什么编译器会说我有Multiple definitions of "myFunction()"
?
我发现了一条线索:当我使用 header.cpp 并删除显示#include "header.hpp"
的行时,程序编译时不会抱怨。 另一方面,如果我删除myFunction
(来自 myLibrary.hpp),程序也会编译而不会出现任何问题
您正在 header 文件中定义 function 的主体。 因此,您在其中包含 header 的每个翻译单元(在本例中为main.cpp
和header.cpp
)最终都会得到它自己的 ZC1C425268E68385D1AB5074C17A94 正文副本。 当您尝试将这些多个单元链接在一起时,您会收到“重复定义”错误。
function需要在hpp文件中声明,在cpp文件中定义:
我的图书馆.hpp
#ifndef LIB_HPP
#define LIB_HPP
#if defined(__unix__)
#include <dlfcn.h>
#include <string>
std::string myFunction();
#endif
#endif
我的图书馆.cpp
#include "myLibrary.hpp"
#if defined(__unix__)
std::string myFunction()
{
return std::string();
}
#endif
//...
您应该在 .cpp 文件中定义函数,而不是在 header 文件中。 您在 header 文件中声明它们。 你正在做的是在 header 文件中定义它,所以当它被包含到多个文件中时,function 会被复制。 跨文件重复符号将引发错误,除非它们是static
。
我的图书馆.cpp:
#include "myLibrary.hpp"
#ifdef(__unix__)
std::string myFunction() { return std::string(); }
#endif
myLibrary.hpp:
#ifndef LIB_HPP
#define LIB_HPP
#if defined(__unix__)
#include <dlfcn.h>
#include <string>
std::string myFunction();
#endif
#endif
包含保护仅防止相同的 header 在同一个翻译单元中包含两次,实际上这通常是一个.cpp
文件。 例如,它可以在执行此操作时防止错误:
#include "header.h"
#include "header.h"
int main()
{
}
但是,更一般地说,这意味着您是否包含已作为另一个 header 的依赖项包含的 header 并不重要。
However, if you have two .cpp files include the same header, and that header contains the definition of a function (such as your myLibrary.hpp
) then each.cpp file will have its own definition (the include guard won't help because header 包含在两个单独的翻译单元 /.cpp 文件中)。
The simplest thing to do is to declare the function in the header, which tells every file that includes your header that the function exists somewhere , and then define it in the.cpp file so that it is only defined once.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.