0

I'm learning c++ and having a bit of trouble with how you share methods with different files and or classes.

if I make a function called increment(int a){a++; return a;}

and have it defined in a.cpp how would I call it in main.cpp? Any help is appreciated, thanks.

Sox Keep You Warm
  • 691
  • 1
  • 9
  • 14

2 Answers2

6
  1. Put int increment(int a); at the top of main.cpp.
  2. Compile both files into object files (with g++, you can use the -c option for that).
  3. Link both files together (with g++, just say g++ main.o increment.o -o increment.exe).

Now, declaring int increment(int a); in every cpp-file that uses this function is very cumbersome. That's why a shortcut exists:

  1. Create a file increment.h with the single line int increment(int a);
  2. Put #include "increment.h" at the top of main.cpp.

Problem with this method is, that increment.h might be included multiple times into a single cpp-file. This is where include guards come in.

Oswald
  • 31,254
  • 3
  • 43
  • 68
0

Use declaration

 int increment(int a);

in the file that wants to call. Usually you #include those declarations form a common file (header) shared by many .cpp files.

Balog Pal
  • 16,195
  • 2
  • 23
  • 37