簡體   English   中英

使用 #ifdef 時的多個定義

[英]Multiple definitions when using #ifdef

我在編譯時遇到問題: Multiple definitions of "myFunction()"我將在這里大大簡化問題。 基本上,我有 3 個文件:“main”、“header”和“myLibrary”。

  • 主文件
    #include "header.hpp"

    int main() {  }
  • header.hpp
    #ifndef HEADER_HPP
    #define HEADER_HPP

    #include "myLibrary.hpp"

    // ...

    #endif
  • header.cpp
    #include "header.hpp"

    // ...
  • 我的圖書館.hpp
    #ifndef LIB_HPP
    #define LIB_HPP

    #if defined(__unix__)
    #include <dlfcn.h>
    std::string myFunction() { return std::string(); }
    #endif

    #endif
  • 我的圖書館.cpp
    #include "myLibrary.hpp"

    //...

那么,為什么編譯器會說我有Multiple definitions of "myFunction()"

我發現了一條線索:當我使用 header.cpp 並刪除顯示#include "header.hpp"的行時,程序編譯時不會抱怨。 另一方面,如果我刪除myFunction (來自 myLibrary.hpp),程序也會編譯而不會出現任何問題

您正在 header 文件中定義 function 的主體。 因此,您在其中包含 header 的每個翻譯單元(在本例中為main.cppheader.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM