多定义错误,包括来自多个源的内联代码的c ++头文件 [英] multiple definition error including c++ header file with inline code from multiple sources

查看:110
本文介绍了多定义错误,包括来自多个源的内联代码的c ++头文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个c + +头文件包含一个类。
我想在几个项目中使用这个类,我不想为它创建一个单独的库,所以我把方法声明和定义在头文件:

I have a c++ header file containing a class. I want to use this class in several projects, bu I don't want to create a separate library for it, so I'm putting both methods declarations and definitions in the header file:

// example.h
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
namespace test_ns{

class TestClass{
public:
    void testMethod();
};

void TestClass::testMethod(){
    // some code here...
}

} // end namespace test_ns
#endif

如果在同一个项目中包含多个cpp文件的头文件,一个错误说 test_ns :: TestClass :: testMethod()的多重定义,而如果我把方法定义放在类体中这不会发生:

If inside the same project I include this header from more than one cpp file, I get an error saying "multiple definition of test_ns::TestClass::testMethod()", while if I put the method definition inside the class body this does not happen:

// example.h
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
namespace test_ns{

class TestClass{
public:
    void testMethod(){
        // some code here...
    }
};

} // end namespace test_ns
#endif

该类是在一个命名空间内定义的,不应该两个形式是等价的吗?为什么该方法被认为在第一种情况下被定义两次?

Since the class is defined inside a namespace, shouldn't the two forms be equivalent? Why is the method considered to be defined twice in the first case?

推荐答案

第二个例子给出了一个隐式的'inline'修饰符,因此编译器会自己协调多个定义(很可能是方法的内部链接,如果它不是内联的)。

These are not equivalent. The second example given has an implicit 'inline' modifier on the method and so the compiler will reconcile multiple definitions itself (most likely with internal linkage of the method if it isn't inlineable).

第一个示例不是内联的,因此如果此标题包含在多个翻译单元中,则您将有多个定义和链接器错误。

The first example isn't inline and so if this header is included in multiple translation units then you will have multiple definitions and linker errors.

头部应该总是被保护以防止在同一翻译单元中的多重定义错误。这应该转换你的标题为:

Also, headers should really always be guarded to prevent multiple definition errors in the same translation unit. That should convert your header to:

#ifndef EXAMPLE_H
#define EXAMPLE_H

//define your class here

#endif

这篇关于多定义错误,包括来自多个源的内联代码的c ++头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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