pcymichael
pcymichael

Reputation: 95

How to use function in other file

I want main.cpp to use run1 function in run.cpp

(In windows)

main.cpp:

int main(){
    run1();
}

run.cpp:

#include<windows.h>

void run1(void){
    int c = 0;
    while(1){
        c++;
        Sleep(1000);
    }
}

If I use g++ main.cpp run.cpp,error occur

error info:

main.cpp: In function 'int main()':
main.cpp:3:5: error: 'run1' was not declared in this scope
     run1();
     ^~~~

Thanks!

Upvotes: 0

Views: 66

Answers (3)

blami
blami

Reputation: 7431

To make function "visible" in other source files than the one where it is defined; you need to create a header file, let's say run.h and put function declaration (you can also put there definition too) in it:

run.h

void run1(void);

Then anywhere you want to use that function you need to include this header file by using #include "run.h" directive.

main.cpp

#include "run.h"
int main(){ run1(); }

You can use header files not only for functions but also for common data types, etc. shared across codebase. For more info on header files I recommend reading Header Files on LearnCPP

Upvotes: 1

Fran Bonafina
Fran Bonafina

Reputation: 150

Call run1.cpp in main.cpp file:

      #include "run1.cpp"

      int main() { run1(); }

And should work.

  • (As best practice, use headers files .h. More info.)

  • Lets check this book from stroustrup who create c++ language, (it´s friendly for read)

Upvotes: 0

Michael Speer
Michael Speer

Reputation: 4962

try a function declaration. these are usually situated in header files ( .hpp )

in your case, having a line that says void run1(void) prior to main in the main.cpp will let main.cpp know that you plan on providing such a function when linking together files later.

it would be best to put that line into a run1.hpp and then including it using #include "run1.hpp" in both main and run1. that way main will know about the function, but if you would change how the function was called or what it returned, then run1.cpp would complain since the declaration in the header would no longer match the actual function.

Upvotes: 1

Related Questions