多个cpp文件中的一个头文件:多个定义

Inp*_*put 1 c++ one-definition-rule inline-functions

我正在尝试访问多个 C++ 文件中的一个头文件。头文件定义如下:

#ifndef UTILS
#define UTILS

void toUpper(string &str) {
    for(unsigned int i=0; i<str.length(); i++) {
            str.at(i) = toupper(str.at(i));
    }
}

void toLower(string &str) {
    for(unsigned int i=0; i<str.length(); i++) {
            str.at(i) = tolower(str.at(i));
    }
}


#endif // UTILS
Run Code Online (Sandbox Code Playgroud)

当我编译代码时,出现以下错误: 在此输入图像描述

据我所知,这不应该返回多个定义,因为我限制代码被定义多次。我还尝试使用预编译指令“#pragma Once”

use*_*570 7

这个问题有两种解决方案。

解决方案1

inline您可以在函数前面添加关键字,例如:

myfile.h

#ifndef UTILS
#define UTILS

inline void toUpper(string &str) {
    for(unsigned int i=0; i<str.length(); i++) {
            str.at(i) = toupper(str.at(i));
    }
}

inline void toLower(string &str) {
    for(unsigned int i=0; i<str.length(); i++) {
            str.at(i) = tolower(str.at(i));
    }
}


#endif // UTILS

Run Code Online (Sandbox Code Playgroud)

现在,您可以将此标头包含在不同的文件中,而不会出现上述错误。

解决方案2

您可以创建一个单独的 .cpp 文件并将定义放在那里。这看起来像:

myfile.h

#ifndef UTILS
#define UTILS

//just declarations here
void toUpper(string &str);    //note no inline keyword needed here

void toLower(string &str);    //note no inline keyword needed here

#endif // UTILS

Run Code Online (Sandbox Code Playgroud)

我的文件.cpp

#include "myheader.h"
void toUpper(string &str) {
    for(unsigned int i=0; i<str.length(); i++) {
            str.at(i) = toupper(str.at(i));
    }
}

void toLower(string &str) {
    for(unsigned int i=0; i<str.length(); i++) {
            str.at(i) = tolower(str.at(i));
    }
}


Run Code Online (Sandbox Code Playgroud)