我正在尝试为自己创建一个通用函数文件。我想做得正确,所以没有 #include .cpp 但 .h 文件。然而,我总是导致 undefined reference 。我用以下三个文件复制了它:
main.cpp:
#include <iostream>
#include "functions.h"
using namespace std;
int main()
{
cout << addNumbers(5,6);
}
functions.h:
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
int addNumbers(int x,int y);
#endif
functions.cpp:
#include "functions.h"
using namespace std;
int addNumbers(int x, int y)
{
return x+y;
}
所有文件都在一个文件夹中。我正在使用 Linux Mint、geany 和 c++11。 编译结果出现以下错误:
main.cpp:(.text+0xf): undefined reference to `addNumbers(int, int)'
不幸的是,我只发现了有关在线类(class)的类似问题。尽管我对编译过程的这一部分一无所知,但我已经了解到这是一个链接问题。在 main() 之前或之后通过原型(prototype)将函数添加到 .cpp 中效果很好。这个问题Undefined reference C++似乎很相似,但我不明白答案。
我的问题是:
我该如何解决这个问题? (我不想将函数包装在类中或将它们添加到 main.cpp 中)
如果可能的话,请解释一下这里出了什么问题。
我想知道是否也可以使用::调用特定函数,因为我已经见过它但从未使用过它,因为我不知道它是如何工作的。
谢谢
最佳答案
不确定 geany 是如何工作的,但基本阶段(在命令行上)是:
- Compile函数.cpp:
g++ -c 函数.cpp
- 编译main.cpp:
g++ -c main.cpp
- Link将它们转化为可执行文件:
g++ -o myprogfunctions.omain.o
从 geany 手册来看,构建似乎仅适用于单文件程序(粗体是我的):
For compilable languages such as C and C++, the Build command will link the current source file's equivalent object file into an executable. If the object file does not exist, the source will be compiled and linked in one step, producing just the executable binary.
和
If you need complex settings for your build system, or several different settings, then writing a Makefile and using the Make commands is recommended; this will also make it easier for users to build your software
解决该问题的工作 makefile 是:
生成文件:
objects = main.o functions.o
AddingNumbersExe : $(objects)
g++ -o AddingNumbersExe $(objects)
main.o : main.cpp functions.h
g++ -c main.cpp
functions.o : functions.cpp functions.h
g++ -c functions.cpp
.PHONY : clean
clean :
-rm AddingNumbersExe $(objects)
创建此文件后,geany 中的“make”选项(Ctrl + F9)起作用。
因此,要处理您的两个文件程序,您需要 Makefile或更强大的 IDE。
关于c++ - 带有头文件的纯函数文件总是导致 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28987762/