10

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

vedro so snegom
  • 307
  • 2
  • 3
  • 8
  • 1
    A good read about this: `Mixing C and C++:` http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html – Lazer Mar 08 '10 at 12:36

2 Answers2

17

Change f.h to:

#ifndef F_H
#define F_H

#ifdef __cplusplus
extern "C" {
#endif

void f();

#ifdef __cplusplus
}
#endif

#endif
Paul R
  • 208,748
  • 37
  • 389
  • 560
2

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

Community
  • 1
  • 1
Jay
  • 24,173
  • 25
  • 93
  • 141