vedro so snegom
vedro so snegom

Reputation: 317

Linking C and CXX files in CMake

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

Upvotes: 11

Views: 11743

Answers (2)

Jay
Jay

Reputation: 24895

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

Upvotes: 2

Paul R
Paul R

Reputation: 212939

Change f.h to:

#ifndef F_H
#define F_H

#ifdef __cplusplus
extern "C" {
#endif

void f();

#ifdef __cplusplus
}
#endif

#endif

Upvotes: 18

Related Questions