[CMake] undefined reference to error when use "c" extension

J Decker d3ck0r at gmail.com
Fri Jun 5 22:33:45 EDT 2015


c++ does name mangling on functions... so functions like 'f' become a much
more complex name (as shown in the xxx not found in your error messages).
In order for C++ to not produce a mangled name C functions have to be
defined as

extern "c" void f( void );
but 'extern "c"' is not liked by C... so you really need to define in the
shared header something like...

#ifdef __cplusplus
#define CEXTERN extern "C"
#ese
#define CEXTERN
#endif

CEXTERN void f( void );

But of course since you don't know about name mangling I guess you don't
know proper header usage either.  This is not a cmake issue, but a general
C++ issue... and you'd do better asking stack exchange or something.

On Fri, Jun 5, 2015 at 6:37 PM, Sunrise <helios.corona at gmail.com> wrote:

>  Hello,
>
> I am linking my code to a library. My code is in C++ but the library is in
> C.
>
> The problem is that whenever the extension of library implementations are "
> c" (not cpp), they are not linked and I get "undefined reference to"
> error.
>
> Here is an example:
>
> Suppose I have
> ./src/main.cpp   // as main file
> ./include/lib.h
> ./include/lib.c  // as a library
>
> And the cmake file is
>
> cmake_minimum_required(VERSION 2.8)
> project(myproj)
>
> set(INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/include)
> include_directories(${INCLUDE_DIR})
> add_library(MY_LIB ${INCLUDE_DIR}/Lib.c)
>
> set(EXECUTABLE_NAME "myproj")
> set(SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src)
> add_executable(myproj ${SOURCE_DIR}/main.cpp)
>
> target_link_libraries(myproj MY_LIB)
>
> This returns undefined reference to error, but if I rename lib.c to
> lib.cpp, everything works fine.
>
> How can I resolve this? I do not want to rename the file to cpp, because
> there are a lot of library files and I prefer to keep the library
> implementations untouched.
>
> Thanks.
>
> --
>
> Powered by www.kitware.com
>
> Please keep messages on-topic and check the CMake FAQ at:
> http://www.cmake.org/Wiki/CMake_FAQ
>
> Kitware offers various services to support the CMake community. For more
> information on each offering, please visit:
>
> CMake Support: http://cmake.org/cmake/help/support.html
> CMake Consulting: http://cmake.org/cmake/help/consulting.html
> CMake Training Courses: http://cmake.org/cmake/help/training.html
>
> Visit other Kitware open-source projects at
> http://www.kitware.com/opensource/opensource.html
>
> Follow this link to subscribe/unsubscribe:
> http://public.kitware.com/mailman/listinfo/cmake
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://public.kitware.com/pipermail/cmake/attachments/20150605/891f6970/attachment.html>


More information about the CMake mailing list