C ++ Error: variable or function is defined in the header file

C ++ Error: variable or function is defined in the header file


1. Background

  There are currently a C ++ project, which includes a1.cpp, a2.cpp, bh, b.cpp a total of four files.

File List

2. Examples of errors

  bh statement Classes B, while the SUM defined int () . b.cpp define B (int x1, int x2) . a1.cpp is the main file, call the class B. a2.cpp also call the class B.

bh code is as follows:

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

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

b.cpp code is as follows:

// 编程工具:vs2017

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

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

a1.cpp code is as follows:

// 编程工具: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 code is as follows:

// 编程工具:vs2017

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

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

Error List

Error message:

1> ------ generation has started: Project: a, Configuration: Debug the Win32 ------
1> a1.cpp
1> a2.cpp
1> B.cpp
1> Generating Code ...
1> LINK : not found C: \ Users \ Administrator \ Desktop \ a \ Debug \ a.exe or on an incremental link does not generate it; performing full link
1> a2.obj: error LNK2005: " public: int __thiscall B :: sum (void) "(? sum @ B @@ QAEHXZ) has been defined in a1.obj in
1> b.obj: error LNK2005:" public: int __thiscall B :: sum (void) "(sum @ B @@? QAEHXZ) has been defined in a1.obj in
1> C: \ Users \ Administrator \ Desktop \ a \ Debug \ a.exe: fatal error LNK1169: find one or more multiply defined symbols of
1> has finished building the project "a. vcxproj "- fAILED.
========== Build: 0 success, a failure, the latest 0, 0 skipped ==========

3. The right approach

  In bh the only statement made in b.cpp for definition. Modified bh code is as follows:

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

Modify b.cpp code is as follows:

// 编程工具:vs2017

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

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

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

operation result:
operation result

4. Summary

  In the header file for only declared, it is not defined.
  Although when only one file called header file data, such as in bh as all definitions and declarations, and delete b.cpp a2.cpp, retention a1.cpp call the class B (that is, only a1.cpp use #include "bh" ), the program does not complain.
  But when multiple files calls the header file data, such as b.cpp, a2.cpp, a1.cpp are included #include "bh", the program will error.

Published 77 original articles · won praise 25 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_34801642/article/details/103718421