簡體   English   中英

聲明變量時,外部未定義參考錯誤

[英]extern undefined reference error when declaring variable

我有2個頭文件和1個源文件可以使用。 分別是: Utility.hGame.hmain.cpp 我在Utility.h聲明了extern變量,並試圖在main.cpp定義它們。 這給了我一個不確定的參考錯誤,我不理解。 我在給變量賦值后使用了變量,這樣應該可以嗎?

Utility.h:

#pragma once

#include <string>
#include <fstream>
#include <SDL.h>

namespace Utility {
    extern std::string BIN_PATH;
    extern std::string ROOT_PATH;
    extern std::string EXE_PATH;

    // Omitted rest of namespace.
}

main.cpp中

#include "Game.h"

int main(int argc, char * argv[]) {
    // Get the necessary paths
    std::string path = SDL_GetBasePath();

    #ifdef _WIN32
        // TODO check if working on different windows systems
        //  exePath = path;
        //  binPath = path.substr(0, path.find_last_of('\\'));
        //  rootPath = binPath.substr(0, binPath.find_last_of('\\'));
    #elif __LINUX__
        Utility::BIN_PATH = path.substr(0, path.find_last_of('/'));
        Utility::ROOT_PATH = Utility::BIN_PATH.substr(0, binPath.find_last_of('/'));
        // TODO check if working on different linux systems
    #endif

    std::cout << "BinPath: " + Utility::BIN_PATH << std::endl;
    std::cout << "RootPath: " + Utility::ROOT_PATH << std::endl;

    // Omitted rest of source.
}

我包括Utility.hGame.h ,並Game.hmain.cpp 鏈接時是否應該將extern定義放在我的main.cpp源代碼上方?

為了稍微簡化(相當復雜)的規則,每個變量(以及其他實體)必須在整個程序中定義一次,並且只能定義一次。 可以多次聲明。 了解什么是聲明和什么定義很重要。

extern std::string var; // in namespace scope

是字符串變量var的聲明。 var尚未定義。 您只需要在其他地方定義一次,即可使用

std::string var; // in namespace scope!

在代碼中,您沒有在函數main定義變量-而是為其分配了值。 但是需要定義變量。

Utility::BIN_PATH = path.substr(0, path.find_last_of('/'));
Utility::ROOT_PATH = Utility::BIN_PATH.substr(0, binPath.find_last_of('/'));

不要定義變量。 他們只是給他們賦值。 要定義它們,請使用:

std::string Utility::BIN_PATH;
std::string Utility::ROOT_PATH;

在全球范圍內。 EXE_PATH添加類似的行。

std::string Utility::EXE_PATH;

您也可以使用

namespace Utility
{
   std::string BIN_PATH;
   std::string ROOT_PATH;
   std::string EXE_PATH;
}

確保這些行顯示在.cpp文件中,而不在.h文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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