问题描述
我最近从 Java 转向 C++,但是现在当我编写应用程序时,我对在 main 函数中编写所有代码不感兴趣,我希望在 main 函数中调用另一个函数,但另一个函数在另一个 .cpp 文件.
I recently moved from Java for C++ but now when I am writing my application I'm not interested in writing everything of the code in the main function I want in main function to call another function but this other function is in another .cpp file.
如果你不明白,让我解释得更好:
我有一个文件:main.cpp
里面有 main 函数.
Let me explain better if you wouldn't understand:
I have one file: main.cpp
inside it I have main function.
我有第二个文件:second.cpp
里面我有一个名为 second()
的函数我想调用这个名为 second()
的函数代码>来自我的主要功能..
I have the second file: second.cpp
inside I have a function called second()
I want to call this function called second()
from my main function..
有什么帮助吗?
推荐答案
您必须使用称为标题"的工具.在标头中声明要使用的函数.然后将其包含在两个文件中.标头是使用 #include
指令包含的单独文件.然后你可以调用另一个函数.
You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include
directive. Then you may call the other function.
void MyFunc();
main.cpp
#include "other.h"
int main() {
MyFunc();
}
other.cpp
#include "other.h"
#include <iostream>
void MyFunc() {
std::cout << "Ohai from another .cpp file!";
std::cin.get();
}
这篇关于在 C++ 程序中使用多个 .cpp 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!