cmake无法构建简单的项目

标签 c cmake

我使用 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/

相关文章:

visual-studio-2008 - CMake-使用Intel编译器生成Visual Studio项目

c++ - 用于具有单个 .h 文件的库的 Cmake

cmake - INSTALL的DESTINATION参数可以为空吗?

static - Cmake:链接共享库

c - 具有两个 pthread 的重复 printf 输出

c - 如何读取文件并将每个读取的行拆分为变量或数组

c++ - 在Ubuntu上使用C++和cmake使用SDL2 + SDL2Image加载PNG

c - 函数 fopen/calloc/malloc 及其替换方法

c - readdir() 问题

c - C 代码中 if 语句的未处理异常