Anson Wong Anson Wong - 1 month ago 6
C++ Question

How to embed config files in C++ VS2015 console application instead of hard-code as const data?

There are lots of answer about simply save it as const data or say converting it to binary data without details.

I have seen this: How to embed a file into an executable?

I do not prefer converting config file into const data.

How could I embed the config file inside the exe when compiled but not next to the exe.

Detailed steps are needed.

Thank You.

Answer

A Windows-specific method is to embed the config file into the executable as a resource:

  • Define an identifier for the resource in some header file, say resource.h:

    #define CONFIG_FILE_RESOURCE_ID 1
    
  • Add a .rc file to your project with the following lines in it:

    #include "resource.h"
    CONFIG_FILE_RESOURCE_ID RCDATA "config.txt"
    

    where config.txt is the name of the file that will be embedded. RCDATA is the type of resource (custom binary data).

    Alternatively, if your version of Visual Studio comes with a resource editor, you could use it.

  • To read the resource from within your program, you must:

    1. Call FindResource(NULL, MAKEINTRESOURCE(CONFIG_FILE_RESOURCE_ID), RT_RCDATA) to get a resource handle.
    2. Call LoadResource(NULL, hrsrc) to convert the resource handle hrsrc to a HGLOBAL.
    3. Use the LockResource and SizeofResource functions to obtain a pointer to the data and the size of the embedded file.

    You may have to supply actual module/instance handles instead of NULL, especially if your code is inside a DLL.

Comments