Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking C and CXX files in CMake

Tags:

c++

c

linker

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

like image 668
vedro so snegom Avatar asked Mar 08 '10 10:03

vedro so snegom


People also ask

What does CXX mean in CMake?

XX stands for "++" (each X is like a "plus" rotated by 45°), CXX stands for "C++".

Can you use CMake with C?

In the C/C++ ecosystem, the best tool for project configuration is CMake. CMake allows you to specify the build of a project, in files named CMakeLists. txt, with a simple syntax (much simpler than writing Makefiles).

Is CMake C or C++?

Installation. C++ CMake tools for Windows is installed as part of the Desktop development with C++ and Linux Development with C++ workloads. Both C++ CMake tools for Windows and Linux Development with C++ are required for cross-platform CMake development.

How does CMake know which compiler to use?

CMake needs a way to determine which compiler to use to invoke the linker. This is determined by the LANGUAGE property of source files of the target , and in the case of static libraries, the LANGUAGE of the dependent libraries. The choice CMake makes may be overridden with the LINKER_LANGUAGE target property.


2 Answers

Change f.h to:

#ifndef F_H
#define F_H

#ifdef __cplusplus
extern "C" {
#endif

void f();

#ifdef __cplusplus
}
#endif

#endif
like image 86
Paul R Avatar answered Sep 25 '22 00:09

Paul R


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

like image 29
Jay Avatar answered Sep 23 '22 00:09

Jay