Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clion undefined reference to function [duplicate]

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.

like image 553
Tomahawk44 Avatar asked Feb 23 '17 19:02

Tomahawk44


1 Answers

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.

like image 129
Seek Addo Avatar answered Oct 18 '22 00:10

Seek Addo