Wednesday, August 22, 2007

How to parse *.ini files with boost

I've spend some time to explore how to use "config_file_iterator" from boost::program_options library. Here is example:
---  config_test.cpp  ---
// Snippet 1: Boost config file parsing
//
#include <iostream>
#include <string>
#include <set>
#include <sstream>

#include <boost/config.hpp>
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>

namespace pod = boost::program_options::detail;

int main()
{
//contents
std::stringstream s(
"a = 1\n"
"b = 2\n"
"c = test option\n");
//parameters
std::set<std::string> options;
options.insert("a");
options.insert("b");
options.insert("c");

//parser
for (pod::config_file_iterator i(s, options), e ; i != e; ++i)
{
std::cout << i->value[0] << std::endl;
}
}
------------------




And more detailed sample:
#include <iostream>
#include <string>
#include <set>
#include <sstream>
#include <exception>
#include <fstream>

#include <boost/config.hpp>
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>

namespace pod = boost::program_options::detail;

int main()
{
std::ifstream config("manager.ini");
if(!config)
{
std::cerr<<"error"<<std::endl;
return 1;
}

//parameters
std::set<std::string> options;
std::map<std::string, std::string> parameters;
options.insert("*");

try
{
for (pod::config_file_iterator i(config, options), e ; i != e; ++i)
{
std::cout << i->string_key <<" "<<i->value[0] << std::endl;
parameters[i->string_key] = i->value[0];
}
std::cout << parameters["StatLogServer.Path"] << std::endl;
}
catch(std::exception& e)
{
std::cerr<<"Exception: "<<e.what()<<std::endl;
}
}

Thursday, August 9, 2007

multiple definition error, cpp

Say you have *.h file with header guards (see below):

#ifndef SOME_HEADER_
#define SOME_HEADER_

int a; //it leads to multiple definition error, because the header guards protect
//multiple inclusion of a header file in a single translation unit
//if you include this file in several translation units then the error
//will occur
//To prevent this, you should move the definition in some implementation file
//or make it inline/static

#endif /*SOME_HEADER_*/

And another one thing on header guards:
//__SOME_HEADER_ - WRONG: two leading underscores, implementation reserved
// _SOME_HEADER_ - WRONG: one leading underscore, implementation reserved
// SOME_HEADER_ - RIGHT: