Function already defined error in C++(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) 的函数,这会在链接时导致名称冲突.
一些可能的解决方案是:
- 将函数声明为静态,这意味着内部链接
- 内联函数
- 将实现从标头中移出并放入 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:
- Declare the functions as static, which implies internal linkage
- Inline the functions
- 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 ++中的函数已定义错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C ++中的函数已定义错误
基础教程推荐
- C语言 structural body结构体详解用法 2022-12-06
- C++详细实现完整图书管理功能 2023-04-04
- C利用语言实现数据结构之队列 2022-11-22
- 详解c# Emit技术 2023-03-25
- C++中的atoi 函数简介 2023-01-05
- C++使用easyX库实现三星环绕效果流程详解 2023-06-26
- C语言基础全局变量与局部变量教程详解 2022-12-31
- C/C++编程中const的使用详解 2023-03-26
- 一文带你了解C++中的字符替换方法 2023-07-20
- 如何C++使用模板特化功能 2023-03-05