首页 > 解决方案 > 链接器错误:未定义对 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*)'

标签: c++cdevice-tree

解决方案


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

用 C 编写的函数应声明为extern "C",以便在 C++ 中可用。许多 C 库都包含了面向用户的头文件

#ifdef __cplusplus
extern "C" {
#endif

// declarations ...

#ifdef __cplusplus
}
#endif

为了方便 C++ 开发人员。

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

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

应该做的伎俩。


推荐阅读