Linker error: undefined reference to fdt_path_offset

Linker error: undefined reference to 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;
}

我compile/link与:

g++ main.cpp -lfdt

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

链接器错误:

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

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

用 C 编写的函数应该用 extern "C" 声明以便在 C++ 中可用。许多 C 库的 user-facing headers 包含在

#ifdef __cplusplus
extern "C" {
#endif

// declarations ...

#ifdef __cplusplus
}
#endif

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

然而 libfdt 显然不会那样做,所以你必须自己做。

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

应该可以解决问题。