链接器错误:对fdt_path_offset的未定义引用

问题描述

我正在尝试利用libfdt来解析设备树blob文件。

您可以通过以下方式在任何Ubuntu上安装libfdt:sudo apt-get install libfdt-dev

我编写了简单的测试程序来使用其中一种API:

#include <vector>
#include <iostream>
#include <libfdt.h>
#include <fstream>

std::vector<char>
read_binary(const std::string& fnm)
{
  if (fnm.empty())
    throw std::runtime_error("No file specified");

  // load the file
  std::ifstream stream(fnm);
  if (!stream)
    throw std::runtime_error("Failed to open file '" + fnm + "' for reading");

  stream.seekg(0,stream.end);
  size_t size = stream.tellg();
  stream.seekg(0,stream.beg);

  std::vector<char> binary(size);
  stream.read(binary.data(),size);
  return binary;
}

int main ()
{
  std::vector<char> binary = read_binary("metadata.dtb");
  const void* fdt = binary.data();
  int offset = fdt_path_offset(fdt,"/interfaces");
  std::cout << offset << std::endl;
  return 0;
}

我编译/链接为:

g++ main.cpp -lfdt

编译成功,但是链接失败。 我不明白为什么。我可以看到图书馆有符号。该库存在于默认搜索路径中。链接器可以找到该库。

链接器错误:

main.cpp: undefined reference to `fdt_path_offset(void const*,char const*)'

解决方法

libfdt是不关心C ++的C软件。

用C编写的函数应使用extern "C"声明,以便在C ++中可用。许多C库的面向用户标头都包裹在

#ifdef __cplusplus
extern "C" {
#endif

// declarations ...

#ifdef __cplusplus
}
#endif

为C ++开发人员提供便利。

但是libfdt显然没有这样做,所以您必须自己做。

extern "C" {
    #include <libfdt.h>
}

应该可以解决问题。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...