我不是基于命令行的编译专家。我使用 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/