C ++中的函数已定义错误

2022-01-25 00:00:00 linker-errors include c++

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

#ifndef SIMPLEFUNCTIONS_H#define SIMPLEFUNCTIONS_H命名空间 my_namespace {双轮(双 r){ 返回(r > 0.0)?地板(r + 0.5):天花板(r - 0.5);}浮动轮(浮动r){返回轮((双)r);}}#endif//SIMPLEFUNCTIONS_H

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

今天我已将它包含在第二个文件中,但它不再有效.在链接时,它告诉我该函数已在firstfile.obj"中定义.

但是,由于我使用的是包含守卫,我希望这些函数只定义一次,还是我遗漏了什么?

解决方案

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

一些可能的解决方案是:

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

在这里阅读更多:什么是外部链接和内部链接?p>

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

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.

相关文章