2017-08-09 104 views
0

我想要做的是一个C++代码,它利用boost库并做一个简单的RS232通信。我得到了这样的代码如下:如何用boost库建立C++代码

#include <boost/asio.hpp> // include boost 
using namespace::boost::asio; // save tons of typing 
#include <iostream> 
using std::cin; 

// These are the values our port needs to connect 
#ifdef _WIN32 
// windows uses com ports, this depends on what com port your cable is plugged in to. 
    const char *PORT = "COM3"; 
#else 
// Mac OS ports 
    const char *PORT = "/dev/tty.usbserial"; 
#endif 
// Note: all the following except BAUD are the exact same as the default values 

serial_port_base::baud_rate BAUD(19200); 
serial_port_base::character_size C_SIZE(8); 
serial_port_base::flow_control FLOW(serial_port_base::flow_control::none); 
serial_port_base::parity PARITY(serial_port_base::parity::none); 
serial_port_base::stop_bits STOP(serial_port_base::stop_bits::one); 

int main() 
{ 
    io_service io; 
    serial_port port(io, PORT); 
    port.set_option(BAUD); 
    port.set_option(C_SIZE); 
    port.set_option(FLOW); 
    port.set_option(PARITY); 
    port.set_option(STOP); 

    unsigned char command[1] = {0}; 

    // read in user value to be sent to device 
    int input; 
    cin >> input; 

    // The cast will convert too big numbers into range. 
    while(input >= 0) 
    { 
     // convert our read in number into the target data type 
     command[0] = static_cast<unsigned char>(input); 
     write(port, buffer(command, 1)); 

     // read in the next input value 
     cin >> input; 
    } 

    // all done sending commands 
    return 0; 
} 

和我建立了代码与下面的命令:

c++ -Iboost_1_64_0 -Lboost_1_64_0/libs/ -stdlib=libc++ PortConfig.cpp -o PortConfig 

但终端不断给我的错误:

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

任何人都可以帮助我在那?提前致谢。

+2

链接所需ibraries:'-lboost_system'或此类。 – user0042

回答

0

编译器选项-Lboost_1_64_0/libs/只是告诉编译器在该目录中查找库。您仍然需要指定要链接的库。根据boost documentation,您将需要boost_system库,因此请将-lboost_system添加到编译器选项中。

修正编译命令应该是这个样子

c++ -Iboost_1_64_0 -Lboost_1_64_0/libs/ -lboost_system -stdlib=libc++ PortConfig.cpp -o PortConfig 
+0

请删除该行“Boost ASIO是一个仅包含头文件的库,因此您无需为此专门链接任何东西。”。 'boost asio'只是头文件,但它依赖于'boost_system',这就是为什么它需要'-lboost_system'被添加到编译器选项。 – kenba

+0

我试过你的解决方案,但给我出现以下错误:ld:库找不到-lboost_system clang:错误:链接器命令失败,退出代码1(使用-v查看调用)。但我确实在该位置安装了增强功能。 –

+0

@kenba你是对的,这是固定的。 – jodag