我在一个可能非常微不足道的问题上被困了几个小时。
这是类最基本的用法。
头文件:person.h
class person
{
protected:
std::string _Name;
public:
void setName(std::string);
};
实现:person.cpp
#include <string>
#include "person.h"
void person::setName(std::string name)
{
_Name = name;
}
驱动:main.cpp
#include <iostream>
#include "person.cpp"
int main()
{
std::cout << "Yes, it worked.\n";
return 0;
}
尝试在 CodeBlocks 中编译此代码时(使用 GNU GCC),出现错误:
~\person.cpp|5|multiple definition of `person::setName(std::string)'|
~\person.cpp|5|first defined here|
||=== Build finished: 2 errors, 0 warnings (0 minutes, 0 seconds) ===|
我在头文件中有原型(prototype),在实现文件中有主体。多重定义在哪里?如果我在 person.cpp 中的“void”之前添加“inline”,它会起作用,但在这种情况下我为什么要这样做?
此外,当在 cmd 中编译与“g++ main.cpp -o main.exe”完全相同的代码时,它工作得很好(没有内联)!
最佳答案
您不需要在 main.cpp 中包含 *.cpp
文件。您需要包含 *.h
文件。
简而言之 - *.cpp
文件包含实现并由编译器编译。 *.h
文件包含定义,可以从 *.cpp
文件中包含。当您包含 *.cpp
文件时,您会得到同一对象的多个定义。
另外,你需要添加include guard
#ifndef MY_HEADER
#define MY_HEADER
... code of your header file ...
#endif
或者只是添加
#pragma once
如果你的编译器支持的话。
关于c++ - 在 CodeBlocks 中编译 C++ 代码时出现多重定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14251425/