Clion undefined reference to function
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.
Tomahawk44
Updated on July 02, 2022Comments
-
Tomahawk44 almost 2 years
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. -
Tomahawk44 about 7 yearsOk, 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!
-
Seek Addo about 7 years@Tomahawk44 don't forget to put all source files(.cpp or .c) in the set source.
-
IInspectable about 7 yearsAs 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.