简体   繁体   中英

Include functions from other cpp(hpp) file with main()

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 , ie to go header only . But that seems to be very inefficient (though acceptable). I think there should be better solutions, ie 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!

Create another header file, eg 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM