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

C++ Calling a function from main within an implementation file

本文关键字:main 调用 函数 实现 文件 C++      更新时间:2023-10-16

假设我的"Main.cpp"文件中有一个函数,我需要在类中的实现.cpp文件中运行。我该怎么做?

假设我有 Main.cpp它有函数 findDate,它需要在我类中名为 Date 的函数中调用。包含 Main.cpp 文件的问题在于所有内容都在重新初始化,我似乎无法让 #ifndef 在 Main.cpp 文件中工作。谢谢!

您应该在文件 main.h 中声明(但不是定义)findDate。然后在需要调用 findDate 的文件顶部包含 .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);

主.cpp:

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

日期.cpp

#include "Main.h"
date
Dates::SomeFunction (void)
{
  return ::findDate ();
}

永远不要包含"Main.cpp",这将创建findDate (...)函数的多个实现和符号(假设该函数未声明为static),并且链接器将无法确定要链接到哪个输出对象。这称为符号冲突多重定义错误。