无法参考该方法

时间:2013-02-02 08:29:41

标签: c++

当我开始学习C ++和算法时。我想在模块范例中对代码进行分组。所以我将排序过程分为3个文件,如下所示:

sort.h

namespace sort
{
    void insertSort(int* a,int size);    
}

sort.cpp

#include "sort.h"
namespace sort
{
}
void sort::insertSort(int* a,int size)
{
    int i,j,key;
    for(j=1;j<size;j++)
    {
        key=a[j];
        i=j-1;
        while(i>=0 && a[i]>key)
        {
            a[i+1]=a[i];
            i=i-1;
        }
        a[i+1]=key;
    }
}

的main.cpp

#include<iostream>
#include"sort.h"
int main()
{
    int a[6]={5,2,4,6,1,3};
    sort::insertSort(a,6);
    for(int i=0;i<6;i++) std::cout<<a[i]<<'\t';
    return 0;
}

当我使用Dev-C ++编译这三个文件时。我收到了以下错误信息:

  

[链接器错误]对`sort :: insertSort(int *,int)'

的未定义引用

我不知道为什么。我想我已经包含了文件“sort.h”,为什么它还告诉我编译不能引用方法sort::insertSort()

1 个答案:

答案 0 :(得分:1)

在构建整个程序时,请确保将所有目标文件链接在一起。链接器抱怨,因为您的main()函数正在调用sort::insertSort函数,该函数已在sort.h声明,但定义其中没有包括在整个计划中。

我不知道哪些参数需要特定的Dev-C ++环境,但通常要确保所有cpp文件都在您发送到编译器前端的命令行中。