2017-10-06 94 views
1

我有以下文件这个简单的代码:没有链接简单的代码

Stat.h

#ifndef STAT_H 
#define STAT_H 

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

#endif 

Stat.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) 

回答

3

您正在重新定义类的Stat.cpp源文件,因为定义也是一个声明。而不是整个类重新定义你只需要在你的Stat.cpp源文件中定义的成员函数(S)和包括Stat.h头:

#include "Stat.h" 

void Stat::compute_value() {}