簡體   English   中英

Linker 錯誤:未定義對 header 文件中的 function 的引用

[英]Linker error: undefined reference to function from header file

確實試圖找到我的具體問題,但我發現最接近的是這個問題,問題出在全局變量上。

我需要制作一個詞法分析器 header 文件及其cpp文件以在main.cpp中使用。 這是兩個詞法分析器文件:

// lexer.hpp
#ifndef LEXER_HPP
#define LEXER_HPP
// Some include files, not really relevant

namespace interpreter
{
    namespace lex
    {
        enum class TokType : char;
        typedef std::vector<std::pair<TokType, std::string>> TokenList;
        typedef std::pair<TokType, std::string> Token;
        TokenList tokenizeString(std::string tokStr);
    } // namespace lex
} // namespace interpreter

#endif
/* --------------------------------------*/
// lexer.cpp
// Again, some not-really-necessary include files
#include "lexer.hpp"
using namespace interpreter::lex;

enum class TokType : char {/* Stuff */};
TokenList tokenizeString(std::string tokStr) {/* Stuff*/};

當我在main.cpp中使用這些東西並編譯時,我收到以下錯誤:

/usr/bin/ld: /tmp/cc3XtuwW.o: in function `main':
main.cpp:(.text+0x7d): undefined reference to `interpreter::lex::tokenizeString(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2: error: ld returned 1 exit status

顯然,我的 function 出了點問題,但我終生無法弄清楚到底出了什么問題。

如果您需要,這里有一些其他信息:

  • 我把我的lexer.cpp變成了一個.o文件。 不過,無論我使用.cpp文件還是.o文件都沒有區別。
  • 我如何編譯main.cppg++ -o main main.cpp lexer.o
  • lexer.hpplexer.cpplexer.omain.cpp都在同一個目錄中。

做這個

TokenList interpreter::lex::tokenizeString(std::string tokStr)
{
    /* Stuff*/
}

或這個

namespace interpreter { namespace lex {
    TokenList tokenizeString(std::string tokStr)
    {
        /* Stuff*/
    }
} }

雖然你說過using namespace interpreter::lex; 這並不意味着新定義的名稱會被添加到interpreter::lex命名空間中。

暫無
暫無

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

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