-1

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Do you have a `B.h` file that declares `age` in it? – NathanOliver Dec 02 '20 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? – Insignificant_guy Dec 02 '20 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](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Dec 02 '20 at 21:32
  • 1
    You can read a bit about it [here](https://yact.tech/en/posts/05_declarations_and_definitions_I.html) and [here](https://yact.tech/en/posts/06_declarations_and_definitions_II.html). – Daniel Langr Dec 02 '20 at 21:33
  • 1
    I would look at the answer provided in this post. https://stackoverflow.com/questions/25274312/is-it-a-good-practice-to-define-c-functions-inside-header-files – boogachamp Dec 02 '20 at 21:35

1 Answers1

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();
    ...
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Maybe add to the answer, that all `.cpp` files must be compiled independently, and in a final step linked together into a executable binary. – datenwolf Dec 02 '20 at 22:58