-2

I have two programs given below in two separate files in c++.

File A.cpp

void name(){
cin>>name;
}

File B.cpp

void age(){
cin>>age;
}

Now, I need to use the function name in file B. Can I do it without rewriting the entire function (name) in file B.cpp? Can I import functions in C++, just like you do in other languages, such as JavaScript?

5
  • Do you have a B.h file that declares age in it? Commented Dec 2, 2020 at 21:28
  • Can we declare functions in .h files in c++? I am sorry, but I am new to c++, so I don't have much idea about it? Can you please explain your answer? Commented Dec 2, 2020 at 21:31
  • 3
    Yes, you can declare functions in a header file. All declarations should go there unless you want them to be "private". Sounds like you could use a good C++ book Commented Dec 2, 2020 at 21:32
  • 1
    You can read a bit about it here and here. Commented Dec 2, 2020 at 21:33
  • 1
    I would look at the answer provided in this post. stackoverflow.com/questions/25274312/… Commented Dec 2, 2020 at 21:35

1 Answer 1

1

Create a header file containing a declaration for the name() function, and then you can #include that header in any source file that needs to access name(), eg:

A.h

#ifndef A_H
#define A_H

void name();

#endif

A.cpp

#include "A.h"

void name(){
    ...
}

B.cpp

#include "A.h"

void age(){
    ...
    name();
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Maybe add to the answer, that all .cpp files must be compiled independently, and in a final step linked together into a executable binary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.