gpt4 book ai didi

c++ - 将定义的函数的函数原型(prototype)放在不同的源文件(不是头文件)中是否合法/好?

转载 作者:行者123 更新时间:2023-11-28 02:31:23 24 4
gpt4 key购买 nike

我不确定我的描述是否恰本地描述了问题。我在尝试了解外部链接和内部链接时发现了这一点。假设我有一个包含 2 个文件的项目:

//A.cpp
#include <iostream>
void doSomething();
int main()
{
doSomething();
return 0;
}

//B.cpp
#include <iostream>
void doSomething()
{
std::cout << "Doing it" << std::endl;
std::cin.get();
}

请注意,这两个文件都不是标题。他们只提供 2 个翻译单元。

我惊讶地发现它可以正确编译和工作。当我在不同的文件中具有相同的效用函数(如线性插值)时,我习惯于编写这样的代码以避免多定义错误:

//A.cpp
#include <iostream>
static void doSomething()
{
std::cout << "Doing it" << std::endl;
std::cin.get();
}
int main()
{
doSomething();
return 0;
}


//B.cpp
#include <iostream>
static void doSomething()
{
std::cout << "Doing it" << std::endl;
std::cin.get();
}
/* some other functions that call doSomething() */

这显然是多余的,上面的做法似乎可以解决。但我想知道这真的是一种公认​​的风格吗?如果没有 IDE 的帮助,人们甚至无法找到函数的定义。

最佳答案

第一段代码是合法的,但不是好的做法。最好创建一个 .h 文件,将函数原型(prototype)和 #include .h 文件放在所有 .cc< 中 使用该函数的文件。

//B.h
#ifndef B_H
#define B_H
void doSomething();
#endif

//A.cpp
#include <iostream>
#include "B.h"
int main()
{
doSomething();
return 0;
}

//B.cpp
#include <iostream>
#include "B.h"

void doSomething()
{
std::cout << "Doing it" << std::endl;
std::cin.get();
}

关于c++ - 将定义的函数的函数原型(prototype)放在不同的源文件(不是头文件)中是否合法/好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28884901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com