Clion 未定义函数引用

Clion undefined reference to function

我有一个简单的程序,其中包含我的 main.cpp、一个头文件 func.h 和另一个源文件 func.cpp。我使用 CLion 2016.3。我的编译器是 gcc.

它们看起来像这样:

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

我的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})

如果我 运行 构建我得到以下错误:

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

我该如何解决这个问题?我搜索了其他类似问题并找到了一些解决方案,但它们对我不起作用,或者我不知道该怎么做。实际上,我在 C 项目中遇到了这个问题,但问题是一样的,我认为解决方案是一样的。
你能帮帮我吗?
非常感谢。

确保在您的 main

中包含 func.h
#include "func.h"

并在 CMakeList.txt 中放入 'func.cpp' set source

在此处明确列出来源。这就是所有(.cpp,.c,.cc)一起编译。如果源文件不在当前目录中,则必须指定源文件的完整路径

set(SOURCE_FILES main.cpp func.cpp)

如果您想在编辑中自动添加文件,可以使用file(GLOB SOURCE_FILES *.cpp)。但请记住,强烈不鼓励这样做 "trick"。