c++ - 带有头文件的纯函数文件总是导致 undefined reference

标签 c++ function c++11 header undefined-reference

我正在尝试为自己创建一个通用函数文件。我想做得正确,所以没有 #include .cpp 但 .h 文件。然而,我总是导致 undefined reference 。我用以下三个文件复制了它:

ma​​in.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++似乎很相似,但我不明白答案。

我的问题是:

  1. 我该如何解决这个问题? (我不想将函数包装在类中或将它们添加到 main.cpp 中)

  2. 如果可能的话,请解释一下这里出了什么问题。

  3. 我想知道是否也可以使用::调用特定函数,因为我已经见过它但从未使用过它,因为我不知道它是如何工作的。

谢谢

最佳答案

不确定 geany 是如何工作的,但基本阶段(在命令行上)是:

  1. Compile函数.cpp:g++ -c 函数.cpp
  2. 编译main.cpp:g++ -c main.cpp
  3. 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/

相关文章:

c++ - 寻找 Boost message_queue 和序列化用法的简单示例

c++ - C++ 或 C 中函数的名称

javascript - setTimeOut 导致函数在单击按钮之前触发

c++ - 将逗号分隔的参数传递给 << 运算符

c++ - 如何使静态导入库依赖于CMake中的另一个静态导入库?

c++ - 使用线程的 vector 和没有加速

java - 为什么这个函数不能像它应该的那样向 ArrayList 添加项目?

javascript - 如何在没有返回选项的情况下完成 JavaScript 中的函数

c++ - 行动手册中 C++ 并发的测试线程安全堆栈示例的生产者和消费者函数

c++ - 迭代基本类型时使用 const 引用有什么缺点吗?