1

I need to compile a set of files that are in c++ and c. I need to do it using a cmakelists.txt.

My set of files are : main.cpp

#include "print_test.h"

int main()
{
 print_test(10);
 return 0;
}

print_test.c

#include <stdio.h>
void print_test(int a)
{
printf("%d", a);
}

print_test.h

void print_test(int a);

It compiles fine with g++ main.cpp print_test.c

But when I use the following CMakeLists.txt It gives linking error

project(print_test)
cmake_minimum_required (VERSION 2.6) 
add_executable(main main.cpp print_test.c)

The error is

[ 66%] Building C object CMakeFiles/main.dir/print_test.c.o
[ 66%] Building CXX object CMakeFiles/main.dir/main.cpp.o
[100%] Linking CXX executable main
CMakeFiles/main.dir/main.cpp.o: In function `main':
main.cpp:(.text+0xa): undefined reference to `print_test(int)'
collect2: error: ld returned 1 exit status
CMakeFiles/main.dir/build.make:98: recipe for target 'main' failed
make[2]: *** [main] Error 1
CMakeFiles/Makefile2:75: recipe for target 'CMakeFiles/main.dir/all' failed
make[1]: *** [CMakeFiles/main.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

My question is how to compile files which use both c and c++ using cmakelists.txt

Jeffrey
  • 11,063
  • 1
  • 21
  • 42
user27665
  • 673
  • 7
  • 27
  • The problem is in using C function from C++ code. This problem is described in [that answer](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix/12574420#12574420) to the duplicate question. – Tsyvarev Apr 16 '20 at 18:22

1 Answers1

1

There is nothing wrong with the CMakeLists.txt as far as I can tell.

The problem is that you to call a C++ function in the C++ translation unit, when such C++ doesn't actually exist. Your intention was presumably to call a the C function. In order to call a C function, you must declare the function appropriately:

extern "C" {
   void print_test(int a);
}
eerorika
  • 232,697
  • 12
  • 197
  • 326