如何使用boost库构建c ++代码

时间:2017-08-09 22:37:07

标签: c++ boost

我想要做的是一个c ++代码,它利用boost库并进行简单的RS232通信。我得到了如下代码:

#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)

任何人都可以帮助我吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

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

更正后的编译命令看起来应该是这样的

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