将定义的函数的函数原型放在不同的源(而不是头)文件中合法/好吗
Is it legal / good to put function prototype of a function defined in a different source (not header) file?
我不确定我的描述是否恰当地描述了这个问题。当我试图理解外部联系和内部联系时,我发现了这一点。假设我有一个包含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
文件,在其中放置函数原型,并在所有使用该函数的.cc
文件中创建#include
.h
文件。
//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();
}
static
关键字表示此函数、对象或变量仅在该转换单元中可用,该转换单元通常是一个cpp文件。您可以在多个cpp文件中拥有多个static doSomething
函数。
关于链接。为了使用功能,提供原型就足够了。这通常在h文件中完成,但您也可以手动提供非静态函数的函数原型。h文件只是用来定义函数库的原型,以便c文件使用它们。正如我所说,你也可以通过其他方式提供原型。由链接器将这些函数链接在一起。
相关文章:
- 用C++在单独的头文件中完成函数体
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 头文件、宏和内联函数c++
- 如何使用单独文件中的派生类访问友元函数对象
- C++无法定义虚拟函数 OUTER 类和头文件
- 回溯C++不打印函数,因此文件
- 如何从另一个文件继承私有成员变量和公共函数
- 从函数角度看ID到文件路径的内部与外部映射
- 区分非成员函数和头文件中的成员函数
- 如何使用对C函数和类对象的外部调用来处理C++头文件
- 如何在其他文件中使用函数
- 整数键映射到头文件中的成员函数指针
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 用"=default"声明的函数应该只在头文件中执行
- 将单独的头文件和类定义文件链接到主函数文件 - G++ 返回重载"undefined reference to"构造函数
- C++ - 在一个函数/文件中初始化变量然后在main()/另一个文件中使用它的最佳方法是什么?
- C++单独的函数文件
- 只对单个函数/文件启用编译器优化