6

I have a simple program with my main.cpp, a header file func.h and another source file func.cpp. I use CLion 2016.3. My compiler is gcc.

They look like this:

Main.cpp

#include <iostream>
#include <stdlib.h>
#include <cstdio>
#include "func.h"

int main() {

int c;
c = number(2);
printf("%i", c);

}

func.cpp

int number(int a){

return a;

}

func.h

#ifndef TEST2_FUNC_H
#define TEST2_FUNC_H

int number(int a);

#endif //TEST2_FUNC_H

My cmakelists.txt

cmake_minimum_required(VERSION 3.6)
project(test2)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(test2 ${SOURCE_FILES})

If i run the build i get the following error:

CMakeFiles\test2.dir/objects.a(main.cpp.obj): In function `main':
C:/Users/name/ClionProjects/test2/main.cpp:8: undefined reference to `number(int)'
....

How can i fix this? I've searched for other similar issues and found some solutions but they didn't work for me or i didn't know what to do. Actually I have this problem with a C-Project but the issue is the same and I think the solution will be the same.
Can you please help me?
Thank you very much.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
Tomahawk44
  • 93
  • 1
  • 1
  • 4

1 Answers1

4

Make sure you include func.h in your main

#include "func.h"

and put 'func.cpp' in CMakeList.txt set source

List the sources explicitly here. That is all (.cpp, .c ,.cc) to compile together. If the sources files are not in the current directory, then you have to specify the full path to the source files

set(SOURCE_FILES main.cpp func.cpp)

You can use file(GLOB SOURCE_FILES *.cpp) if you want to automatically add files in your compilation. But keep in mind that this "trick" is strongly not encouraged to do.

inorik
  • 147
  • 9
Seek Addo
  • 1,871
  • 2
  • 18
  • 30
  • Ok, thanks a lot. I thought i have tried these things, especially putting the func.cpp in my cmakelist.txt but apparently i did something wrong before^^. Now it works. Thanks! – Tomahawk44 Feb 23 '17 at 19:39
  • @Tomahawk44 don't forget to put all source files(.cpp or .c) in the set source. – Seek Addo Feb 23 '17 at 19:42
  • As always, an answer is so much more helpful, if it explained, what the issue is and how the proposed solution addresses it. As written it merely teaches readers, what to do, without knowing why. This is known as [cargo cult programming](https://en.wikipedia.org/wiki/Cargo_cult_programming). – IInspectable Feb 23 '17 at 20:41