简体   繁体   English

在 main.cpp 问题中从单独的 C++ 文件调用函数

[英]Calling functions from separate C++ files in main.cpp trouble

I have been searching online for solutions to this rather simple problem.我一直在网上搜索这个相当简单的问题的解决方案。 My goal is to call a function from a separate .cpp file in my main.cpp file.我的目标是从我的 main.cpp 文件中的单独 .cpp 文件中调用一个函数。 What I have found thus far has told me to define my function in a separate .cpp file (averageScore.cpp) which looks like:到目前为止我所发现的告诉我在一个单独的 .cpp 文件(averageScore.cpp)中定义我的函数,它看起来像:

void averageScore()
{
    "Blah, Blah, Blah"
}

And then declare the function as a prototype in a header file (Lesson1.h) which looks like:然后在头文件(Lesson1.h)中将该函数声明为原型,如下所示:

#include "C:/averagescore.cpp"
void averageScore();

And finally call the function again in the main.cpp:最后在 main.cpp 中再次调用该函数:

#include "Lesson1.h"
int main()
{
    averageScore();
    return 0;
}

I am currently a CS student and my overall objective with this method of organization and execution is to create a single project for all of the rudimentary programs we must create on a weekly basis instead of creating a new project for every single program.我目前是一名 CS 学生,我使用这种组织和执行方法的总体目标是为我们必须每周创建的所有基本程序创建一个项目,而不是为每个程序创建一个新项目。 For reference, I am using VScode and have used the following link to help me thus far:作为参考,我正在使用 VScode,并且到目前为止已经使用以下链接来帮助我:

http://www.cplusplus.com/forum/beginner/97779/ http://www.cplusplus.com/forum/beginner/97779/

My condolences and gratitude are extended to anyone who has taken the time to read through this and help me out!我向所有花时间阅读本文并帮助我的人表示哀悼和感谢!

To achieve what you want, you must create a header file, and declare your function there, for example:为了实现你想要的,你必须创建一个头文件,并在那里声明你的函数,例如:

lesson1.h第1课.h

void averageScore();

In a .cpp file, you define that function and include the header you just created:在 .cpp 文件中,您定义该函数并包含您刚刚创建的标头:

lesson1.cpp课程1.cpp

#include "lesson1.h"

void averageScore(){
    // Do what you want in this function
}

Then you can call that function in your main.cpp by including "lesson1.h":然后你可以通过包含“lesson1.h”在你的 main.cpp 中调用该函数:

main.cpp主程序

#include "lesson1.h"

int main()
{
    averageScore();
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM