[CMake] Building a library for both C and C++

Eric Wing ewmailing at gmail.com
Wed Jan 9 11:08:51 EST 2013


>
> On Wed, Jan 9, 2013 at 1:17 AM, kgardenia42 <kgardenia42 at googlemail.com>

>> So, lets say I have foo.c, bar.c and baz.c and I would like to build
>> mylib.a and mylib++.a
>>

I concur with the others that usually this is unnecessary and simply
building a C library with extern "C" guards for C++ is usually
sufficient.

Though as somebody who has been burned by C++ way too many times, I am
aware of nasty cases where compiling as C or C++ does make a
difference. Two examples off the top of my head:
- set/long jump vs. exception handling: mixing the two is a bad idea.
I actually have a really esoteric case of this in a patch I wrote for
Lua to enable Objective-C exception handling which adds another layer
of complexity because there are interactions with C++ exception
handling if you want to compile in support for it. But usually you
have #ifdefs for this kind of stuff in your code.
- function pointers: Function pointers are not guaranteed to work
across C and C++ calling conventions. Some platforms have a different
calling convention for C++ and if you try passing/using a C++ function
pointer to a function that is extern "C", it may not work correctly.

But most people don't worry about these things and writing a C library
is the most portable/compatible thing you can do. C++ users are used
to self-inflicted wounds so making them handle any subtle
incompatibility repercussions is the norm.

Anyhow, if you really need to build two libraries, I don't necessarily
have a good solution for you, but one idea is to use CMake to copy
your .c file into a .cpp file on the fly and add it to a second
separate C++ library target.

-Eric
-- 
Beginning iPhone Games Development
http://playcontrol.net/iphonegamebook/


More information about the CMake mailing list