在 C++ 程序中使用多个 .cpp 文件?

Using multiple .cpp files in c++ program?(在 C++ 程序中使用多个 .cpp 文件?)
本文介绍了在 C++ 程序中使用多个 .cpp 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我最近从 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 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)
STL BigInt class implementation(STL BigInt 类实现)
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)