[CMake] Building a static C library with internals in C++
William A. Hoffman
billlist at nycap.rr.com
Fri May 5 09:05:38 EDT 2006
At 08:22 AM 5/5/2006, Eric BOIX wrote:
> Dear cmake users,
>
>Consider a library (let's call it MyLib) whose internal code is written
>in C++ and whose API is written in C (in order not to constrain MyLib users
>to use C++ vs C). Hence MyLib is the aggregation of the compilation of
>C source files (e.g. for the code implementing the API itself) and of C++
>source files.
>
>Now consider a user of MyLib trying to link his C written calling code
>user.c against MyLib. Add the fact that this is a nice and behaved user
>that uses cmake for his building process. :)
>
>Now, they are two cases depending on the choice of library he made when
>he build MyLib: either a dynamic (or shared) library or a static library
>(which corresponds respectively to ON and OFF for the BUILD_SHARED_LIBS
>cmake internal variable).
>
>1/ When MyLib library was build in shared mode, then cmake properly build
> a MyLib.so (on linux for illustrating things) which correctly depends on
> libstdc++ (which can be seen e.g. with "ldd MyLib.so"). This is because the
> command generated by cmake to build MyLib.so is based on g++ (sorry for
> the GNU bias) which calls the linker and adds on the fly the required
> libs e.g. libstdc++. [Don't quote me on this one, though].
> Nevetheless when the user links his C compiled user.o against MyLib.so things
> run smoothly.
>
>2/ BUT when MyLib library was build in static mode, the produced MyLib.a has no
> reference to libstdc++. This is because the command used to build MyLib.a
> is now simply "ar" (which has no knowledge of the internals of the
> object files it is aggregating).
> Hence when the user links his C compiled user.o against MyLib.a the
> linker fails to resolve the symbols required by the C++ part of MyLib
> (which are in libstdc++)...
> Allthough this can be fixed manually by linking with g++ this is not
> really satisfying for the user...who has no reason to specify
> libstdc++ as target library to it's EXECUTABLE target (for the good
> reason that he might not even be aware of the fact that MyLib uses C++
> for it's internals).
>
>Here is my question:
>how to deal cleanly (i.e. in a nice portable cmake way) with such a situation ?
You can set the LINKER_LANGUAGE on the executable.
SET_TARGET_PROPERTIES(myexe PROPERTIES LINKER_LANGUAGE CXX)
I have added some docs to SET_TARGET_PROPERTIES, as follows:
"The LINKER_LANGUAGE property is used to change the tool "
"used to link an executable or shared library. The default is "
"set the language to match the files in the library. CXX and C "
"are common values for this property."
-Bill
More information about the CMake
mailing list