More on link-time backwards compatibility

May 4, 2009 at 1:00 pm (Programming/Development)

I want to address the problem with not understanding linker behavior as I mentioned a couple entries ago.

If one doesn’t understand linker behavior and link-time compatibility issues, seemingly harmless edits can lead to incompatibilities with existing libraries and dll’s. This is a particular concern with externally accessible public headers or functions existing in shared libraries, etc.

For example, take the following function:

int fooFunc(char* fooStr, int barNum)

Let’s say another parameter is needed in order to perform some new functionality, so you change the function definition to this:

int fooFunc(char* fooStr, int barNum, int newNum=0)

Cleverly, you add the new parameter with a default value so that calls to the previous format of the function will work! Excellent! Let’s commit this sucker and hit up YouTube!

Not so fast…

Sure, this code will compile just fine because it is compile time compatible with existing code, but if this function is part of a shared library, it will break compatibility with code deployed from that library. This is because the C++ mangled name for this function will change to match the new function profile.
Aside from having anyone using this shared library recompiling & linking against this change, there is a simple way to include this kind of change while maintaining backwards, link-time compatibility.

All you do is create a new function and implement the old function in terms of the new one.

Here’s what I mean:


int fooFunc(char* fooStr, int barNum);
int fooFunc(char* fooStr, int barNum, int newNum);

Note that there is no default value on the new parameter anymore. That is because you have to specify every value to use it anyway. Observe:


int fooFunc(char* fooStr, int barNum, int newNum)
int fooFunc(char* fooStr, int barNum)
   fooFunc(fooStr, barNum, 0);

Now, we have both the original definition which will avoid link-time errors with existing shared libraries while also including the change for anyone requiring it.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: