不会link,除非内联方法

Will not link, unless inlining method

我在 link 时遇到了一个奇怪的错误。

headers:

global.h

#include <cmath>
#include <iostream>
#include <vector>

#include <blitz/tinyvec2.h>
typedef blitz::TinyVector<double,3> vettore;

#include "animal.h"

animal.h

#ifndef __ANIMAL_H
#define __ANIMAL_H


//! basic data structure for an animal -------------------------
struct Animal
{
   int age;
public:
   Animal(int _age) : age(_age) {}
};


//! contains info about a pair of animals ----------------------
struct AnimalPairs
{
  vettore distance;

  AnimalPairs( const vettore& _distance ) : distance(_distance) {}
};
typedef std::vector<AnimalPairs> pair_list;


//! data structure for a group of animals ----------------------
class AnimalVector
{
private:
  std::vector<Animal> animals;
  pair_list pairs;

public:
  AnimalVector( const  AnimalVector &other );

};

#endif

这里是 *cpp 个文件

main.cpp

#include "global.h"
int main ()
{
   std::cout<< "Hello" << std::endl;
}

animal.cpp

#include "global.h"

AnimalVector::AnimalVector( const AnimalVector &other )
{
  pairs = other.pairs;
}

为了编译我使用 g++ main.cpp animal.cpp -I/usr/include/boost -I/fs01/ma01/homes/matc/local/blitz/include

这是我得到的错误:

/tmp/ccGKHwoj.o: In function `AnimalPairs::AnimalPairs(AnimalPairs const&)':
animal.cpp:(.text._ZN11AnimalPairsC2ERKS_[_ZN11AnimalPairsC5ERKS_]+0x1f):
undefined reference to \`blitz::TinyVector<double,
3>::TinyVector(blitz::TinyVector<double, 3> const&)'
collect2: error: ld returned 1 exit status

出于某些原因,如果我将 AnimalVector 构造函数设置为 inline,代码将起作用。 有人可以解释一下为什么吗?

编辑: 这是 link 到 blitz/tinyvec2.h https://github.com/syntheticpp/blitz/blob/master/blitz/tinyvec2.h

tinyvec2.cc 是您使用 tinyvec2.h

中声明的方法时需要包含的文件

我不喜欢那个命名(一个名为 .cc 的包含文件)并且在得到你得到的错误之前我自己会忽略它。

但如果您查看该 .cc 文件的内容,就会清楚其预期用途。

在类似的情况下(文件对的命名规则非常不同)我使用以下编码习惯用法:

第一个包含文件(它们的 .h)包含在需要其中任何一个的任何其他 .h 文件中。第二个包含文件永远不会被其他 .h 文件包含。

当您收到表明其中某些文件丢失的构建错误时,请将第二个包含文件的包含添加到出现构建错误的任何 .cpp 文件中。

该计划对于在大型项目中保持快速构建速度并最大限度地减少复杂交互模板之间的循环依赖非常有效类。但这可能不是将 tinyvec2 分成两个包含文件的人所想的。

底线:您看到的任何出现 link 错误的模块都需要在编译时包含 .cc 文件,但直接还是间接取决于您。在你的 global.h 中包含 .cc 更简单,最坏的情况下会降低你的构建速度(因为这个 .cc 与你自己的 .h 文件没有循环关系)。