Monday, September 3, 2018

Using C++ Resource Files with Eclipse

Using a resource file in Eclipse is possible. While writing a blog about how to develop Windows programs using Eclipse and C++ I ran into a problem that I needed a tool for, namely to quote C++ code in the blog. So, I wrote a little program in C++ using the techniques I was discussing, but later I decided it would be an ideal project to rewrite using a resource file (.rc). There are a few things you have to do to get it to work.

First, Eclipse doesn’t provide the slick resource file editor that you find in Visual C++. This means that to edit the .rc file you will need to use a text editor. This isn’t particularly hard to do, but I did find myself questioning whether I was gaining anything by using the resource file over just making the calls I needed in the C++ code. One thing that I can say that I don’t like is that you must use #define in the header file rather than defining constants with static const or as an enum.

Second, the .rc file has to be compiled using a special compiler and then you have to link to the .o that is generated. In order to prevent yourself from having to remember to do that each time you modify the .rc file, you must create a pre-build step. Even then, changes to the .rc file won’t compile and link unless you’ve mode changes to the C++ source code.

As with the other blog post, you can download the Eclipse project for this program. It isn’t cleaned up, but it should provide you with an example of how to compile a resource file using Eclipse and MinGW. The command to run the winres must be supplied to Eclipse via the settings window of the C/C++ Build properties.

This command is:

c:\mingw\bin\windres.exe --include-dir="${ProjDirPath}" --input="${ProjDirPath}/res.rc" --output="${ProjDirPath}/res.o" --define RESLOC="${ProjDirPath}/resources.h"

Notice that I provide the project directory path for both the input and the output. For some reason, MinGW doesn’t seem to recognize –include-dir, but I populate it anyway. I also define a macro RESLOC. You will see this used within the .rc file where we include resources.h, since winres can’t find the local directory on its path.

#define Q(x) #x
#define QUOTE(x) Q(x)
#include QUOTE(RESLOC)

#define APSTUDIO_HIDDEN_SYMBOLS
#include "windows.h"
#undef APSTUDIO_HIDDEN_SYMBOLS

The rest is pretty much the same as you would expect for a resource file and in many cases you can copy on that has been created with Visual Studio, if you don’t want to edit it by hand.

The Eclipse Project is located at: http://www.timothyfish.com/Examples/Windows4Eclipse/BlogCodeFormat.zip