boost::lexical_cast minimal example

#include <boost/lexical_cast.hpp>
#include <iostream>

int main() {
    int a = boost::lexical_cast<int>("123");
    int b = boost::lexical_cast<int>("456");
    int c = a + b;
    std::cout << c << std::endl; //Prints 579


Posted by Uli Köhler in Boost, C/C++

How to fix boost::program_options “error: ‘po’ has not been declared”

If you want to compile your C++ project using boost::program_options but you see error messages like

/home/uli/myProject/main.cpp:28:5: error: ‘po’ has not been declared
     po::notify (vm);

you are missing this declaration which you need to place directly after #include <boost/program_options.hpp>:

namespace po = boost::program_options;

This declares po as an alias for the boost::program_options namespace, because writing po::variables_map is much easier to read than boost::program_options::variables_map and using namespace boost::program_options might cause some name collisions with other functions.

Posted by Uli Köhler in Boost, C/C++

How to add boost::program_options to your CMake build

Simply add these lines to the end of your CMakeLists.txt and replace myTarget by the name of your build target (usually the first argument to add_executable(...) or add_library(...)):

# Include boost
find_package( Boost 1.30 COMPONENTS program_options REQUIRED )
target_include_directories( myTarget PRIVATE ${Boost_INCLUDE_DIR})
target_link_libraries( myTarget ${Boost_LIBRARIES} )

If you have multiple targets, copy & paste the last two lines for each target.

If you need a specific version of boost, replace 1.30 by the minimum version you need.

Posted by Uli Köhler in Boost, C/C++, CMake