我有一个函数在我的所有头文件和main.cpp中是相同的,如果我在main.cpp中定义它们一旦它们被包含它们都能够使用它还是会有编译器问题?
这整个头文件业务还是新手.提前致谢.
在头文件(myfunction.h)中,您只需要声明函数:
int foo(int param);
Run Code Online (Sandbox Code Playgroud)
在main.cpp(或任何其他cpp文件 - 更好的选择myfunction.cpp- 只是确保定义包含在一个文件中!)文件中,您需要定义函数:
int foo(int param)
{
return 1;
}
Run Code Online (Sandbox Code Playgroud)
在您正在使用函数的所有其他源(cpp)文件中foo,只需包含myfunction.h并使用函数:
#include "myfunction.h"
void someotherfunction()
{
std::cout << foo(1) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
编译器只需要在使用之前查看函数的声明.链接器将函数的定义与您使用该函数的位置连接起来.如果您忘记在main.cpp文件中编写定义,则不会获得编译器,但会出现链接器错误.值得一提的是,编译器正在单独编译每个cpp文件,而链接器的工作是组合所有编译器目标文件并生成最终输出文件.在大多数设置中,链接器将在编译后自动调用,因此您可能不熟悉它.
如果在头文件中包含整个函数定义,那么将在包含头文件的每个转换单元中编译该定义,并且您将获得multiple symbol definition链接器错误或类似的东西 - 这就是为什么您只需要在头文件中包含函数的声明文件.但是,也有例外 - 例如,您可以声明您的功能inline- 其他答案解释了这种方法.
所以,现在myfunction.h包含函数声明:
#ifndef MY_FUNCTION_H
#define MY_FUNCITON_H
// declaration
int myfunction();
#end if
Run Code Online (Sandbox Code Playgroud)
myfunction.cpp 包含函数定义:
int myfunction()
{
return 4;
}
Run Code Online (Sandbox Code Playgroud)
现在,在file1.cpp和file2.cpp中你想使用这个函数,所以你要包括myfunction.h:
// file1.cpp
#include "myfunction.h"
// somewhere in the file
void foo()
{
std::cout << myfunction();
}
Run Code Online (Sandbox Code Playgroud)
......并在第二个文件中:
// file2.cpp
#include "myfunction.h"
// somewhere in the file
void bar()
{
/// ...
std::cout << myfunction();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
707 次 |
| 最近记录: |