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

Matthew Woehlke matthew.woehlke at kitware.com
Wed Jan 9 13:50:33 EST 2013


On 2013-01-09 12:53, kgardenia42 wrote:
> On Wed, Jan 9, 2013 at 8:57 AM, Nils Gladitz <gladitz at sci-vis.de> wrote:
>> Why do you want to build a C library both with a C++ and a C compiler?
>> Wouldn't a C compiler build and an extern "C" interface suffice to use the
>> library with both C and C++?
>
> I didn't fully qualify my use-case.
>
> Let's say I have source files:  foo.c, foo.cpp and bar.c
>
> I would like to build:
>
> * a C library (mylib.a) containing foo.c and bar.c
> * a C++ library (mylib++.a) containing foo.cpp and bar.c

Maybe I am confused... if bar.c does not contain C++ source code, what 
is the problem building bar.c with the C compiler and linking in into 
your C++ library?

IOW (overly simplified example), I would expect this to work:

add_library(my_c_lib foo.c bar.c)
add_library(my_cpp_lib foo.cpp bar.c)


If you really have to, you could get clever and do something like:

# replace B with your build dir, e.g. CMAKE_CURRENT_BINARY_DIR
add_custom_target(
   OUTPUT ${B}/bar.cpp
   DEPENDS bar.c
   COMMAND ${CMAKE_COMMAND} -E copy ${B}/bar.cpp bar.c
)
add_library(my_cpp_lib foo.cpp ${B}/bar.cpp)

-- 
Matthew



More information about the CMake mailing list