带有头文件的纯函数文件总是导致未定义的引用

Pure functions file with header file always resulting in undefined reference

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

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() 之前或之后将函数添加到 .cpp 中可以正常工作。这个问题 Undefined reference C++ 好像很相似,但我不明白答案。

我的问题是:

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

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

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

谢谢

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

  1. Compile functions.cpp: g++ -c functions.cpp
  2. 编译main.cpp:g++ -c main.cpp
  3. Link 将它们转化为可执行文件:g++ -o myprog functions.o main.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。