C++错误:在头文件中定义变量或函数

C++错误:在头文件中定义变量或函数


1. 背景

  当前有1个C++项目,其中包含a1.cpp、a2.cpp、b.h、b.cpp共4个文件。

文件列表

2. 错误实例

  b.h声明类B,同时定义int sum()。b.cpp定义B(int x1, int x2)。a1.cpp是主文件,调用类B。a2.cpp也调用类B。

b.h代码如下:

#pragma once
class B
{
public:
	int b1;
	int b2;
	B(int x1, int x2);
	int sum();
};

int B::sum()
{
	return b1 + b2;
}

b.cpp代码如下:

// 编程工具:vs2017

#include "pch.h"
#include "b.h"

B::B(int x1, int x2)
{
	b1 = x1;
	b2 = x2;
}

a1.cpp代码如下:

// 编程工具:vs2017

#include "pch.h"
#include <iostream>
#include "b.h"
using namespace std;

int main()
{
	B b(1, 2);
	cout << b.sum();
	return 0;
}

a2.cpp代码如下:

// 编程工具:vs2017

#include "pch.h"
#include <iostream>
#include "b.h"
using namespace std;

int a2()
{
	B b(3, 4);
	cout << b.sum();
	return 0;
}

错误列表

错误提示:

1>------ 已启动生成: 项目: a, 配置: Debug Win32 ------
1>a1.cpp
1>a2.cpp
1>b.cpp
1>正在生成代码…
1>LINK : 没有找到 C:\Users\Administrator\Desktop\a\Debug\a.exe 或上一个增量链接没有生成它;正在执行完全链接
1>a2.obj : error LNK2005: “public: int __thiscall B::sum(void)” (?sum@B@@QAEHXZ) 已经在 a1.obj 中定义
1>b.obj : error LNK2005: “public: int __thiscall B::sum(void)” (?sum@B@@QAEHXZ) 已经在 a1.obj 中定义
1>C:\Users\Administrator\Desktop\a\Debug\a.exe : fatal error LNK1169: 找到一个或多个多重定义的符号
1>已完成生成项目“a.vcxproj”的操作 - 失败。
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========

3. 正确做法

  在b.h中只作声明,在b.cpp中作定义。修改后b.h代码如下:

#pragma once
class B
{
public:
	int b1;
	int b2;
	B(int x1, int x2);
	int sum();
};

修改b.cpp代码如下:

// 编程工具:vs2017

#include "pch.h"
#include "b.h"

B::B(int x1, int x2)
{
	b1 = x1;
	b2 = x2;
}

int B::sum()
{
	return b1 + b2;
}

运行结果:
运行结果

4. 总结

  在头文件中只作声明,不作定义。
  虽然当只有1个文件调用头文件中数据,如在b.h中作所有定义和声明,删除b.cpp和a2.cpp,保留a1.cpp调用类B(即只有a1.cpp使用#include “b.h”),程序不会报错。
  但当多个文件调用头文件中数据,如b.cpp,a2.cpp,a1.cpp中都包含#include “b.h”,程序一定会报错。

发布了77 篇原创文章 · 获赞 25 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_34801642/article/details/103718421