Linking C and CXX files in CMake

10,831

Solution 1

Change f.h to:

#ifndef F_H
#define F_H

#ifdef __cplusplus
extern "C" {
#endif

void f();

#ifdef __cplusplus
}
#endif

#endif

Solution 2

Please add C guards to all your C files. Refer to this link for more details

Share:
10,831
vedro so snegom
Author by

vedro so snegom

Updated on June 12, 2022

Comments

  • vedro so snegom
    vedro so snegom almost 2 years

    I'm building C++ app with CMake. But it uses some source files in C. Here is simplified structure:

    trunk/CMakeLists.txt:

    project(myapp)
    set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -g -Wall")
    add_subdirectory (src myapp)
    

    trunk/src/main.cpp:

    #include "smth/f.h"
    int main() { f(); }
    

    trunk/src/CMakeLists.txt:

    add_subdirectory (smth)
    link_directories (smth)    
    set(APP_SRC main)
    add_executable (myapp ${APP_SRC})
    target_link_libraries (myapp smth)
    

    trunk/src/smth/f.h:

    #ifndef F_H
    #define F_H
    void f();
    #endif
    

    trunk/src/smth/f.c:

    #include "f.h"
    void f() {}
    

    trunk/src/smth/CMakeLists.txt

    set (SMTH_SRC some_cpp_file1 some_cpp_file2 f)
    add_library (smth STATIC ${SMTH_SRC})
    

    The problem is: i run gmake, it compiles all the files and when it links all libs together, i get:

    undefined reference to `f()` in main.cpp
    

    if i rename f.c into f.cpp everything goes just fine. What's the difference and how to handle it?

    Thanks