2014-06-12

Exporting symbols

I am porting PngOptimizer to Linux, and more specifically I am targeting vanilla Ubuntu, so I am learning to use the GTK+ framework to create the GUI.

I have been facing a very strange bug with GTK+ as soon as I started linking my custom framework which is exposed as a static library. Its name is "chustd" and contains some basic classes to manage strings, compression, images, etc.

GTK+ was refusing to initialize. A simple program containing just those lines:

int main(int argc, char** argv)
{
	gtk_init(&argc, &argv);
	return 0;
}

would either crash or do nothing but output a lot of GTK errors.

The nice thing with Linux is that you can usually find the source code of any library, so I have been able to dig into the problem.

I was shocked discovering that my executable was exporting all the symbols of the static libraries it was linked to and that a system library was eventually calling... one of the symbols of my executable! The symbol was a function of the zlib I statically embed in the chustd, which conflicted with a system dynamic library built from the zlib source.

wrong call with exported symbols

This is very unusual when you are used to develop on Windows. On Windows, with Visual Studio C++ compiler, no symbols is exported unless you specifically ask for it, with a declspec(dllexport) declaration before a function or a variable. GCC, at the contrary, exports everything unless you told him not to do so. That can lead to some unexpected results as the one I was experiencing.

Fortunately, there is a solution. It consists in changing GCC default behavior by informing him that all symbols are "hidden" unless otherwise specified. It means they should not be considered as symbols to be dynamically linked. It's done by adding the -fvisibility=hidden option when building an application or a static library. The symbols will still be present but will be flagged as not exported.

Voilą, I solved my problem and can resume my journey with GTK+ ^^