简体   繁体   中英

why "#define BOOST_ASIO_ENABLE_HANDLER_TRACKING 1" doesn't work as expected?

Reference:

https://www.boost.org/doc/libs/1_78_0/doc/html/boost_asio/overview/core/handler_tracking.html https://www.boost.org/doc/libs/1_78_0/doc/html/boost_asio/example/cpp11/handler_tracking/async_tcp_echo_server.cpp

Based on the documentation, when enabled by defining BOOST_ASIO_ENABLE_HANDLER_TRACKING , Boost.Asio writes debugging output to the standard error stream.

I made the following changes to the source code of async_tcp_echo_server.cpp .

 17 #define BOOST_ASIO_ENABLE_HANDLER_TRACKING 1
 18 using boost::asio::ip::tcp;

Above the using boost::asio::ip::tcp; , I added #define BOOST_ASIO_ENABLE_HANDLER_TRACKING 1 and expect this will trigger the debugging track. However, it doesn't work.

$ g++ -std=gnu++2a -Wall -g -ggdb -Werror -I /usr/include/boost -pthread async_tcp_echo_server.cpp -o async_tcp_echo_server
$ ./async_tcp_echo_server 3333
^C

Instead, I removed the added macro definition from the source code and added -DBOOST_ASIO_ENABLE_HANDLER_TRACKING to the command line for the compiler and now it works as expected.

$ g++ -std=gnu++2a -Wall -g -ggdb -Werror -I /usr/include/boost -pthread async_tcp_echo_server.cpp -o async_tcp_echo_server -DBOOST_ASIO_ENABLE_HANDLER_TRACKING
$ ./async_tcp_echo_server 3333
@asio|1645642051.016866|0^1|in 'do_accept' (async_tcp_echo_server.cpp:95)
@asio|1645642051.016866|0*1|socket@0x7ffec2082aa8.async_accept
@asio|1645642051.017322|.1|non_blocking_accept,ec=system:11

From g++ online manual,

-D name Predefine name as a macro, with definition 1.

Question > Why the macro definition within the source code doesn't work?

Thank you

As the commenter helpfully pointed out: you have to define the preprocessor define before the first inclusion of any (.) Asio header.

However, there's another reason why specifying it in your build script is FAR superior.

Using BOOST_ASIO_ENABLE_HANDLER_TRACKING breaks interface. It must be defined in every translation unit participating in a link or else you will have undefined behaviour (ODR violations). See eg Valgrind errors from boost::asio

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM