简体   繁体   English

C ++从实现文件中的main调用函数

[英]C++ Calling a function from main within an implementation file

Say that I have a function within my "Main.cpp" file that I need to run within an implementation .cpp file that is within a class. 假设我的“ Main.cpp”文件中有一个函数,我需要在一个类中的实现.cpp文件中运行该函数。 How would I go about this? 我将如何处理?

Say I have Main.cpp that has function findDate and it needs to be called within a function that is in my class called Dates. 假设我有具有函数findDate的Main.cpp,它需要在我的类中称为Dates的函数中调用。 The problem with including the Main.cpp file is that everything is getting re-initialized and I cannot seem to get the #ifndef to work within a Main.cpp file. 包含Main.cpp文件的问题是,所有内容都在重新初始化,而我似乎无法让#ifndef在Main.cpp文件中工作。 Thanks! 谢谢!

You should declare (but not define) findDate in a file main.h. 您应该在文件main.h中声明(但不定义)findDate。 Then include the .h file at the top of the file where findDate needs to be called. 然后,在需要调用findDate的文件顶部包含.h文件。

Here is the general procedure for doing this. 这是执行此操作的一般步骤。

Create a file called Main.h: 创建一个名为Main.h的文件:

#pragma once // Include guard, so you don't include multiple times.

// Declaration (it is okay to have multiple declarations, if they
//              have a corresponding definition somewhere)
date findDate (void);

Main.cpp: Main.cpp:

// Definition (it is not okay to have multiple non-static definitions)
date
findDate (void)
{
  // Do some stuff
  return something;
}

Dates.cpp Dates.cpp

#include "Main.h"

date
Dates::SomeFunction (void)
{
  return ::findDate ();
}

Never include "Main.cpp", this will create multiple implementations and symbols of your findDate (...) function (assuming the function is not declared static ), and the linker will be unable to figure out which output object to link to. 永远不要包含“ Main.cpp”,这将创建findDate (...)函数的多个实现和符号(假设该函数未声明为static ),并且链接器将无法确定要链接到哪个输出对象。 This is known as a symbol collision or multiple definition error. 这被称为符号冲突 或多定义错误。

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

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