我使用 clion 1.0 和 cmake 并尝试构建简单的演示项目。但 cmake 不想将外部 .c 文件链接到 main.c。
系统:Xubuntu 14.04
main.c
#include "common/source_file.h"
void SetupRC()
{
Cmake_dermo(1);
}
int main(int argc, char* argv[])
{
SetupRC();
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.2)
project(mytest)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES main.cpp)
add_executable(mytest common/source_file.h common/source_file.c ${SOURCE_FILES})
源文件.c
#include "source_file.h"
void Cmake_dermo(int da)
{
da += 1;
}
出了什么问题?
最佳答案
我尝试了CMakeList.txt
,我得到了
In function SetupRC(): main.cpp:(.text+0xa): undefined reference to Cmake_dermo(int)
问题来自于不同语言混合的事实:
- main.cpp 是 C++,编译器是 C++ 编译器。
- source_file.c 是 C 语言,因为它是一个 .c 文件。
要包含对 C 的引用的 header ,请阅读 this question 。更正后的 main.cpp 文件如下所示:
extern "C"
{
#include "common/source_file.h"
}
void SetupRC()
{
Cmake_dermo(1);
}
int main(int argc, char* argv[])
{
SetupRC();
return 0;
}
头文件如下所示:
#ifndef SOURCE_FILE_H_ /* Include guard */
#define SOURCE_FILE_H_
void Cmake_dermo(int da);
#endif // SOURCE_FILE_H_
看来 Cmake 可以处理不同的语言,而无需对 CMakeList.txt 进行任何修改。
关于cmake无法构建简单的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31428146/