C++ 无法链接简单代码

C++ 无法链接简单代码,c++,linker,C++,Linker,我在以下文件中有这个简单的代码: 统计 #ifndef STAT_H #define STAT_H class Stat { public: void compute_value(); }; #endif 统计cpp class Stat { public: void compute_value() { } }; main.cpp #include "Stat.h" int main(void) { Stat st

我在以下文件中有这个简单的代码:

统计

#ifndef STAT_H
#define STAT_H

class Stat {
    public:
        void compute_value();
};

#endif
统计cpp

class Stat {
    public:
        void compute_value() {
        }
};
main.cpp

#include "Stat.h"

int main(void)
{
    Stat stat;
    stat.compute_value();
}
当我尝试编译时,出现以下错误:

clang++ -std=c++14 -Wall -Wextra -pedantic -Weverything -O3 Stat.cpp main.cpp -o main
/tmp/main-0466d7.o: In function `main':
main.cpp:(.text+0xf6a): undefined reference to `Stat::compute_value()'
clang: error: linker command failed with exit code 1 (use -v to see invocation)

您正在Stat.cpp源文件中重新定义该类,因为该定义也是一个声明。不需要重新定义整个类,只需在Stat.cpp源文件中定义成员函数并包含Stat.h头:

#include "Stat.h"

void Stat::compute_value() {}