c++ - 如何使用 clang++ 链接到 boost in/usr/local 编译?

标签 c++ macos boost clang asio

我不是基于命令行的编译专家。我使用 boost official example 中的代码开发了以下 asio UDP 应用程序.

// udpServer.cpp

#include <boost/asio.hpp>
#include <iostream>
#include <array>

using boost::asio::ip::udp;

int main()
{
  try
  {
    boost::asio::io_service io_service;

    udp::socket socket(io_service, udp::endpoint(udp::v4(), 13));

    for (;;)
    {
      std::array<char, 1> recv_buf;
      udp::endpoint remote_endpoint;
      boost::system::error_code error;
      socket.receive_from(boost::asio::buffer(recv_buf), remote_endpoint, 0, error);

      if (error && error != boost::asio::error::message_size)
        throw boost::system::system_error(error);

      std::string message = "some_string";

      boost::system::error_code ignored_error;
      socket.send_to(boost::asio::buffer(message), remote_endpoint, 0, ignored_error);
    }
  }

  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}

我使用 Macports 安装了 boost 1.59,因为这是我使用 sudo port install boost 得到的版本。我看到 boost 位于我的 /usr/local/lib 和标题中 /usr/local/include

我尝试了其他讨论的建议,但代码无法编译,因为它无法链接到 boost。我在 OSX 上并尝试使用以下命令使用 clang 进行编译

clang++ -std=c++14 udpServer.cpp

试过了

clang++ -std=c++14 -I /usr/local/include/boost -L /usr/local/lib udpServer.cpp

但出现以下错误:

Undefined symbols for architecture x86_64:
"boost::system::system_category()", referenced from:
  boost::asio::error::get_system_category() in udpServer-4b9a12.o
  boost::system::error_code::error_code() in udpServer-4b9a12.o
  ___cxx_global_var_init.2 in udpServer-4b9a12.o
"boost::system::generic_category()", referenced from:
  ___cxx_global_var_init in udpServer-4b9a12.o
  ___cxx_global_var_init.1 in udpServer-4b9a12.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

最佳答案

试试这个:

clang++ -std=c++14 -I /usr/local/include -L /usr/local/lib -lboost_system udpServer.cpp -o updServer

您将头文件包含为 <boost/asio.hpp> , 所以只需传递 -I /usr/local/include . -I -L让链接器知道在哪里可以找到头文件和库。您还需要让链接器知道您实际需要通过 -l<library_name> 链接的库。 .

顺便说一下,/usr/local/include是默认标题搜索路径,/usr/local/lib是默认库搜索路径。所以你可以:

clang++ -std=c++14 -lboost_system udpServer.cpp -o updServer

关于c++ - 如何使用 clang++ 链接到 boost in/usr/local 编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43820525/

相关文章:

c++ - 使用函数创建数组 - Objective-C++

c++ - 什么是最接近 Pex for Visual C++ 的东西?

macos - 在OS X上构建OpenSSH:配置:警告:sandbox.h:存在,但无法编译

macos - 是否可以将 Google Chrome Canary 设置为 OS X Yosemite 上的默认浏览器?

python - 使用 boost::python 包装 boost::optional

c++ - weak_ptr 的性能损失是多少?

c++ - 好友声明不转发声明

c++ - 我应该如何在 C++ 中转换 malloc 的结果?

python - Xcode gcc 退出状态 1

c++ - boost::shared_ptr 直接替换