多重c ++文件导致“多重定义”错误? [英] Multple c++ files causes "multiple definition" error?

查看:815
本文介绍了多重c ++文件导致“多重定义”错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次在一个项目中使用多个C ++文件。两者都需要包括一个protected(#ifndef)头文件。但是,当我这样做,我得到一个多重定义错误。

I'm using multiple C++ files in one project for the first time. Both have need to include a protected (#ifndef) header file. However, when I do that, I get a multiple definition error.

我有两个.cpp文件直接调用头,一个间接(另一个include包括它),然后两个其他头文件,包括它。

What I have is two one .cpp file that calls the header directly, and one indirectly (Another include includes it) and then two other header files that include it.

那么,我需要做什么来摆脱错误呢?

So what do I need to do to get rid of the error?

错误:


obj\Debug\main.o ||在函数 Z14sortLibQtyTest4BookS _':|
[PATH] \miscFuncs.h | 16 |多个定义
sortLibQtyTest(Book,Book)'

obj\Debug\main.o||In function Z14sortLibQtyTest4BookS_':| [PATH]\miscFuncs.h|16|multiple definition ofsortLibQtyTest(Book, Book)'

CODE:

bool sortLibQtyTest(Book a, Book b){ return a.getQty() > b.getQty(); }

应该提到,这不是给我的唯一功能,是的,有些不那么短而甜。

It should be mentioned that this isn't the only function giving me problems, probably more than ten are, and some aren't so short and sweet. Also, the functions are needed in multiple files.

推荐答案

您有两个选项来解决这个多重定义问题:标记方法内联,或将定义放在.cpp文件中。

You have two options to solve this multiple definition problem: Mark the method inline, or put the definition in a .cpp file.

1)标记方法内联:

// Foo.h

inline bool foo(int i) { return i = 42; }

2)将定义放在 .cpp file:

2) Put the definition in a .cpp file:

// Foo.h

inline bool foo(int i); // declaration

// Foo.cpp
bool foo(int i) { return i = 42; } // definition

编译器在第一种情况下实际上是否内联方法与此无关: inline 允许您在头文件中定义非成员函数,而不会违反一个定义规则。

Whether the method is actually inlined by the compiler in the first case is irrelevant here: inline allows you to define a non-member function in a header file without breaking the one definition rule.

这篇关于多重c ++文件导致“多重定义”错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆