vendredi 29 juillet 2022

Use global function from library in C++ with local variables

I have created a library in C++ in which I have a function similar to the following:

originalmain.cpp

executionTimer * timer;

//This function is available to every other class through a global header file
calculateTime(){
    timer->returnTime() 
}

main(){
    foo(); // a function that eventually calls calulateTime()
    return 0;
}

foo.cpp

#include "globals.h"
void foo(){
   ....
   calculateTime();
   ...

When foo() calls calculateTime(), the global function defined in main.cpp executes.

I have created a library from those files which I'm using in another program like so:

mymain.cpp

#include "globals.h"

// trying to redefine the executionTime global object
// and the global calculateTime function to use it
executionTime * timer2; 
calculateTime(){
    timer2->returnTime()
}

main(){
   foo(); // I want foo to run normally, but now use timer2 instead of timer
   ...
   return 0;
}

From my understanding, since I'm using the library, I should have access to the functions/classes etc defined there. and indeed I have in most of them.

Things go wrong when foo() is calling 'calculateTime'. In that case I would expect calculateTime() from mymain.cpp to be executed, but instead I see the one from main.cpp.

So I have the following questions:

  1. Why is this happening?
  2. Is there a way to fix it?

Best regards

Aucun commentaire:

Enregistrer un commentaire