【问题标题】:undefined reference in c++C++中未定义的引用
【发布时间】:2015-12-05 19:21:54
【问题描述】:

这是我遇到的错误。

-bash-4.1$ g++ strl.cpp -o -lc-
/tmp/ccRpiglh.o: In function `main':
strl.cpp:(.text+0xf): undefined reference to `plusplus'
collect2: ld returned 1 exit status

Hear 是 strl.cpp 的源代码。这是一个重复我的问题的简单示例。

strl.cpp
#include <iostream>
#include <stdlib.h>
#include "libc-.h"

using namespace std;

int main()
{
  cout<<plusplus(5,2)<<'\n';
}

这里是 libc.cpp 的源代码

libc.cpp
#include <iostream>

using namespace std;

int plusplus(int a, int b)
{
  return a + b;
}

libc-.h 的源代码

libc-.h 
#ifndef _SCANTYPE_H_
#define _SCANTYPE_H_

#include <iostream>
#include <stdlib.h>

#ifdef __cplusplus
extern "C"
{
#endif

  using namespace std;

  int plusplus(int a, int b);

#ifdef __cplusplus
}
#endif 

#endif

我正在编译以下内容:

g++ -Wall -shared -fPIC -o libc-.so libc-.cpp
g++ strl.cpp -o -lc-

g++ -Wall -shared -fPIC -o libc-.so libc-.cpp 编译没有错误。

为什么函数plusplus 是一个未定义的引用?

感谢您对我做错的任何见解。

【问题讨论】:

标签: c++ shared-libraries undefined-reference


【解决方案1】:

libc-.h 中的“使用”是做什么用的? 无论如何,在我看来,您也需要将此标头包含在 libc.cpp 中。见https://stackoverflow.com/a/1380926/2406949

【讨论】:

    【解决方案2】:

    在函数定义周围不需要extern C 吗?我敢打赌,链接器正在尝试将损坏的 C++ 名称与未损坏的 C 名称匹配。

    请注意,您正在使用 C++ 功能 (using),因此检查 #ifdef cplusplus 是多余的。如果它是假的,你的编译将失败。

    【讨论】:

      【解决方案3】:

      缺少对plusplus() 的引用,因为它没有提供。你很有希望

      `int plusplus(int a, int b);`
      

      libc-.h 中有C 链接,但在libc.cpp 中没有兑现您的承诺。 要解决此问题,请将后一个文件更改为

      // libc.cpp
      #include <iostream>
      #include "libc-.h"   // include proto-type which has C linkage
      
      int plusplus(int a, int b)
      {
        return a + b;
      }
      

      另外,您应该从不在头文件中使用using namespace std;

      【讨论】:

        猜你喜欢
        • 2013-01-08
        • 1970-01-01
        • 2020-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-21
        相关资源
        最近更新 更多