Fat-chunk Fat-chunk - 29 days ago 4
YAML Question

How do I provide default YAML configuration values in a static library?

I have a configuration file system written in C++ which uses the yaml-cpp library to parse and write to YAML files. I have this as part of my static library.

I would like the ability to return a default value for a field that is requested by a user of the library (calling from their code), but which has not been defined in the user's YAML file.

For example say the user wants to use the field

from their custom

int bar = config_reader.read<int>( "config.yaml", "foo" );

If they have
foo: 10
in their
will be set to 10. However I would also like to provide a default value (for example 4) in the case where
is omitted from

There are two possibilities I have thought of:

  1. Have a set of static maps between field names and default values in a cpp file which gets compiled into the static library, however I will need to have different maps for different types and I feel this could get messy with type checking and maybe requiring template specialization methods.

  2. Have a YAML file which contains all of the default values for expected fields, which the configuration system falls back on if it cannot find the field in the user's config file. I think this would be the preferred solution for me, but I cannot think of a neat way of packaging this YAML file. I would rather the user didn't have to copy or point to this file each time they set up a new project linking the static library.


I would provide the defaults in a YAML file in a global (i.e. non-user specific place) and allow to override the values with user-specific ones. Consider just throwing an error if the global defaults are missing an entry, this will not happen by accident.

The global defaults you can put in /etc/default/YOUBLIBNAME.yaml. The user's configuration nowadays mostly follows the XDG base directory specification. For that use $XDG_CONFIG_HOME/YOURLIBNAME/config.yaml if XDG_CONFIG_HOME is set in the environment, if not set use $HOME/.config/YOURLIBNAME/config.yaml.

If your library has to work under Windows, I would put the user specific data under %APPDATA% in a subdir YOURBLINAME.