【问题标题】:C++: Including header-file fails compilation but including source cpp file compilesC++:包含头文件编译失败,但包含源 cpp 文件编译
【发布时间】:2009-09-27 20:29:09
【问题描述】:

这可能真的很简单,但它阻碍了我在 C++ 道路上的前进。 我目前正在阅读加速的 C++,我决定过度使用其中的一个练习。这一切都运行良好,我的代码运行良好,直到我将其拆分为头文件和单独的源文件。当我导入包含我编写的一些函数的 .cpp 源文件时,一切运行正常。但是,当我尝试通过头文件导入函数时,它会严重失败,并且出现以下错误。 我正在使用 Geany 的 gcc 进行编译,到目前为止一切正常。感谢您的帮助。

错误:

g++ -Wall -o "quartile" "quartile.cpp" (in directory: /home/charles/Temp)
Compilation failed.
/tmp/ccJrQoI9.o: In function `main':
quartile.cpp:(.text+0xfd): undefined reference to `quartile(std::vector<double, std::allocator<double> >)'
collect2: ld returned 1 exit status

“stats.h”:

#ifndef GUARD_stats_h
#define GUARD_stats_h

#include <vector>

std::vector<double> quartile(std::vector<double>);

#endif

“stats.cpp”:

#include <vector>
#include <algorithm>
#include "stats.h"

using std::vector;    using std::sort;

double median(vector<double> vec){
     //code...
}

vector<double> quartile(vector<double> vec){
     //code and I also reference median from here.
}

“四分位数.cpp”:

#include <iostream>
#include <vector>
#include "stats.h" //if I change this to "stats.cpp" it works

using std::cin;       using std::cout;
using std::vector;

int main(){
    //code and reference to quartile function in here.
}

【问题讨论】:

    标签: c++ gcc header-files


    【解决方案1】:

    编译失败,因为你只声明了这个函数。它的定义在不同的编译单元中,您没有将这两者链接在一起。

    执行g++ -Wall -o quartile quartile.cpp stats.cpp 即可。

    【讨论】:

    • 非常感谢,我说的很简单,但您所节省的痛苦令人难以置信。我在看书的时候想知道,我不知道stats.h是如何找到stats.cpp的,只是相信它会使用一些魔法,就像python的import一样。
    【解决方案2】:

    你需要告诉 g++ 两个 .cpp 输入文件。我不是 g++ 方面的专家,但它看起来像是一个链接器错误。

    喜欢

    g++ -Wall -o "quartile" "quartile.cpp" "stats.cpp"

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 2012-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多