简体   繁体   中英

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. 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. 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. Thanks!

You should declare (but not define) findDate in a file main.h. Then include the .h file at the top of the file where findDate needs to be called.

Here is the general procedure for doing this.

Create a file called 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:

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

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. This is known as a symbol collision or multiple definition error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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