2

I'm use clion 1.0 with cmake and try to build simple demo project. But cmake don't want link external .c file to main.c.

System: 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})

source_file.c

#include "source_file.h"

void Cmake_dermo(int da)
{
    da += 1;
}

What is wrong?

Maxim Palenov
  • 650
  • 7
  • 17

2 Answers2

1

You're using the wrong filename in your CMakeLists.txt file.

Change the line in your CMakeLists.txt from:

set(SOURCE_FILES main.cpp)

to:

set(SOURCE_FILES main.c)
user5071535
  • 1,312
  • 8
  • 25
  • 42
1

I tried you CMakeList.txt and i got

In function SetupRC(): main.cpp:(.text+0xa): undefined reference to Cmake_dermo(int)

The problem comes from the fact that different languages are mixed:

  • main.cpp is C++ and the compiler is a C++ compiler.
  • source_file.c is C, since it is a .c file.

To include a header featuring reference to C, read this question. A corrected main.cpp file looks like:

extern "C"
{
  #include "common/source_file.h"
}

void SetupRC()
{
  Cmake_dermo(1);
}

int main(int argc, char* argv[])
{
  SetupRC();

  return 0;
}

The header file looks like:

#ifndef SOURCE_FILE_H_   /* Include guard */
#define SOURCE_FILE_H_

void Cmake_dermo(int da);

#endif // SOURCE_FILE_H_

It seems that Cmake takes care of the different languages without any modification to the CMakeList.txt.

Community
  • 1
  • 1
francis
  • 9,525
  • 2
  • 25
  • 41