【问题标题】:Linking C and CXX files in CMake在 CMake 中链接 C 和 CXX 文件
【发布时间】:2010-03-08 10:57:51
【问题描述】:

我正在使用 CMake 构建 C++ 应用程序。但是它使用了一些 C 语言的源文件。这是简化的结构:

主干/CMakeLists.txt:

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

主干/src/main.cpp:

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

主干/src/CMakeLists.txt:

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

主干/src/smth/f.h:

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

主干/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})

问题是:我运行 gmake,它编译所有文件,当它将所有库链接在一起时,我得到:

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

如果我将 f.c 重命名为 f.cpp,一切都会很好。有什么区别以及如何处理?

谢谢

【问题讨论】:

标签: c++ c linker cmake


【解决方案1】:

将 f.h 更改为:

#ifndef F_H
#define F_H

#ifdef __cplusplus
extern "C" {
#endif

void f();

#ifdef __cplusplus
}
#endif

#endif

【讨论】:

    【解决方案2】:

    请在您的所有 C 文件中添加 C 保护。更多详情请参考link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 2017-08-04
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      • 1970-01-01
      相关资源
      最近更新 更多