1

I am using C++ for some sequence data analysis, and have found it hard to call functions across files. Say I have a file A.cpp with an associated header A.hpp. A.cpp has a Main() function and a function My_Func() that I hope to reuse in B.cpp, which also has a Main() function. My question is, how do I call My_Func() from B.cpp? I am not allowed to compile A.cpp and link it with B.cpp since it will create two entry points (two mains) for the program.

The solution I can think of is to implement My_Func() in A.hpp instead of A.cpp and include A.hpp in B.cpp, i.e. to go header only. But that seems to be very inefficient (though acceptable). I think there should be better solutions, i.e. in python I can just do from A import My_Func. I am wondering what would be a canonical way to deal with this issue cleanly? Thanks in advance!

  • 3
    Looks like you need additional `shared.cpp` and `shared.hpp` files which will declare and define shared function to be used in (other) various compilation object. – Alex Lop. Jul 12 '21 at 05:06
  • @AlexLop. Thanks! Seems there are no cleaner solutions. I will go with that then – George Wang Jul 12 '21 at 05:13
  • note, it's undefined behaviour to have the same function name in two different files, unless `static` – M.M Jul 12 '21 at 05:32

1 Answers1

1

Create another header file, e.g. common.hpp and declare the function definition of My_Func() in that header file.

Then, create another cpp file, common.cpp and implement the function inside there.

Now, if you include common.hpp in both of A.cpp and B.cpp, calling My_Func() will work from both A.cpp and B.cpp.

UkFLSUI
  • 5,509
  • 6
  • 32
  • 47