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

Time:02-24

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|[email protected]_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

CodePudding user response:

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 e.g. Valgrind errors from boost::asio

  • Related