我在Ubuntu上写C++,运行程序时遇到error:
ThinkBook-15p:/data150/study/projects/0408$ g++ -g ./src/*.cpp -I ./include -o ./bin/test01
In file included from ./include/Camel.hpp:2:0,
from ./include/Alpaca.hpp:2,
from ./src/test01.cpp:2:
./include/Animal.hpp:9:7: error: redefinition of ‘class Animal’
class Animal{
^~~~~~
In file included from ./include/Sheep.hpp:3:0,
from ./include/Alpaca.hpp:1,
from ./src/test01.cpp:2:
./include/Animal.hpp:9:7: note: previous definition of ‘class Animal’
class Animal{
^~~~~~
产生原因: #include 导入了重复到类。这种问题很难避免,#include 的.h文件中,经常分别#include到相同到.h, 比如:这个例子中, Animal.h就被重复导入了。
解决方法 1:
在Animal.h 开头加上:
#pragma once
表示无论Animal.h被导入几次,都只当作1次。
解决方法2:
将Animal.h 文件中到class Animal放到下面代码中
#ifndef Animal_H
#define Animal_H
******
#endif
比如:
#include <iostream>
using namespace std;
#ifndef Animal_H
#define Animal_H
class Animal{
public:
int m_Age;
};
#endif
完美解决:
ThinkBook-15p:/data150/study/projects/0408$ g++ -g ./src/*.cpp -I ./include -o ./bin/test01
ThinkBook-15p:/data150/study/projects/0408$ ./bin/test01
20
20