C++代码中存在未定义的引用错误

Undefined reference error in C++ code

本文关键字:引用 错误 未定义 存在 代码 C++      更新时间:2023-10-16

你好,我在编译代码时收到此错误:

main.cpp:(.text.startup+0xfc): undefined reference to `CMyMath::melFilterBank(std::vector<double, std::allocator<double> >, int, int, int)'
collect2: error: ld returned 1 exit status
make: *** [bin/main.elf] Error 1

my.h文件:

#ifndef _MYMATH_H_
#define _MYMATH_H_
#define _USE_MATH_DEFINES
#include <vector>
#include <stdio.h>
#include <cmath>
#include <stdint.h>
#include <complex> 
class CMyMath
{
    public:
        CMyMath();  
        ~CMyMath();
        std::vector<double> melFilterBank(std::vector<double> signal, int frequency, int band_num, int coef_num);
};
#endif

我的.cpp文件:

#include "MyMath.h"    
CMyMath::CMyMath()
{
    printf("constructor calledn");
}   
CMyMath::~CMyMath()
{
    printf("destructor calledn");
}
std::vector<double> melFilterBank(std::vector<double> ourSignal, int frequency, int bandNum, int coefNum)
{
    std::vector<double> output; //ck in matlab code
    /*
    DO SOME STUFF
    */
    return output;
}

main:

#include <stdio.h>
#include <vector>
#include <cmath>
#include "MyMath.h"
int main()
{
    class CMyMath a;
    std::vector<double> mel {0.0000001,0.0000005,0.0000004,0.0000005};
    a.melFilterBank(mel,8000,6,5);
    return 0;
}

你认为哪里应该出错?我是C++的新手,我真的不知道出了什么问题。你有什么建议?

定义(在.cpp文件中)需要指定您定义的是成员函数,而不是单独的非成员函数:

std::vector<double> CMyMath::melFilterBank(std::vector<double> ourSignal, int frequency, int bandNum, int coefNum)
                    ^^^^^^^^^
std::vector<double> CMyMath :: melFilterBank(std::vector<double> ourSignal, int frequency, int bandNum, int coefNum)

定义时,成员函数需要以类名为前缀。