函数已在C ++中定义错误 [英] Function already defined error in C++

查看:112
本文介绍了函数已在C ++中定义错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为"SimpleFunctions.h"的文件,定义如下:

#ifndef SIMPLEFUNCTIONS_H
#define SIMPLEFUNCTIONS_H

namespace my_namespace {

double round(double r) { return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5); }
float round(float r) { return round((double)r); }

}

#endif // SIMPLEFUNCTIONS_H

此文件以前仅包含在一个文件中,并且工作正常.

现在,我已经将其包含在第二个文件中,并且不再起作用.在链接时,它告诉我该函数已在"firstfile.obj"中定义.

但是,由于我使用的是包含保护,我希望这些功能只能定义一次,还是会丢失某些内容?

解决方案

默认情况下,这些函数具有外部链接.这意味着每个翻译单元都具有称为double round(double r)和float round(float r)的功能,这会在链接时引起名称冲突.

一些可能的解决方案是:

  1. 将函数声明为静态,这意味着内部链接
  2. 内联函数
  3. 将实现移出标头并移入c/c ++文件

在此处了解更多信息: 什么是外部链接和内部链接?

顺便说一下,包含保护可以防止单个翻译单元多次包含头文件.与您在这里看到的问题不同.

I have a file called "SimpleFunctions.h" defined as follow:

#ifndef SIMPLEFUNCTIONS_H
#define SIMPLEFUNCTIONS_H

namespace my_namespace {

double round(double r) { return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5); }
float round(float r) { return round((double)r); }

}

#endif // SIMPLEFUNCTIONS_H

This file was previously included in only one file and it was working fine.

Now today I have included it in a second file and it no longer works. At link time, it tells me that the function is already defined in "firstfile.obj".

However, since I am using include guards, I would expect the functions to be defined only once, or am I missing something?

解决方案

By default, these functions have external linkage. That means each translation unit has functions called double round(double r) and float round(float r), which causes a name collision at link time.

Some possible solutions are:

  1. Declare the functions as static, which implies internal linkage
  2. Inline the functions
  3. Move the implementation out of the header and into a c/c++ file

Read more here: What is external linkage and internal linkage?

By the way, include guards protect a single translation unit from including a header file multiple times. That's a different issue that what you're seeing here.

这篇关于函数已在C ++中定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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