链接器错误:头文件中对函数的未定义引用 [英] Linker error: undefined reference to function from header file

查看:51
本文介绍了链接器错误:头文件中对函数的未定义引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没有试图找到我的特定问题,但发现的最接近的问题是

当我在 main.cpp 中使用这些东西并进行编译时,出现以下错误:

 /usr/bin/ld:/tmp/cc3XtuwW.o:在函数main中:main.cpp:(.text+0x7d):未定义引用`interpreter::lex::tokenizeString(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'collect2:错误:ld返回1退出状态 

很明显,我的功能出了点问题,但是我无法终生发现什么实际上是错的.

如果需要,还有其他一些信息:

执行此操作

  TokenList解释器:: lex :: tokenizeString(std :: string tokStr){/* 东西*/} 

或这个

 命名空间解释器{名称空间lex {TokenList tokenizeString(std :: string tokStr){/* 东西*/}}} 

尽管您说过使用名称空间解释器:: lex; 并不意味着新定义的名称已添加到 interpreter :: lex 命名空间中.

I did try to find my specific issue, but the closest I found was this question where the issue was with global variables.

I need make a lexer header file along with it's cpp file to use in main.cpp. here are the two lexer files:

// 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*/};

When I use this stuff in main.cpp and compile, I get the following error:

/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

Clearly, something is wrong with my function, but I cannot for the life of me figure out what is actually wrong.

Here's some other information if you need it:

  • I turned my lexer.cpp into a .o file. Whether I use the .cpp file or the .o file does not make a difference, though.
  • How I compiled main.cpp: g++ -o main main.cpp lexer.o
  • lexer.hpp, lexer.cpp, lexer.o and main.cpp are all in the same directory.

解决方案

Do this

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

or this

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

Although you've said using namespace interpreter::lex; that doesn't mean that newly defined names get added to the interpreter::lex namespace.

这篇关于链接器错误:头文件中对函数的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆