[英]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.我正在使用 C++ 进行一些序列数据分析,并且发现很难跨文件调用函数。 Say I have a file
A.cpp
with an associated header A.hpp
.假设我有一个文件
A.cpp
与关联的标题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. A.cpp
有一个Main()
函数和一个My_Func()
函数,我希望在B.cpp
重用,它也有一个Main()
函数。 My question is, how do I call My_Func()
from B.cpp
?我的问题是,如何从
B.cpp
调用My_Func()
? 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.我不允许编译
A.cpp
并将其与B.cpp
链接,因为它将为程序创建两个入口点(两个主干线)。
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 .我能想到的解决方案是实现
My_Func()
在A.hpp
代替A.cpp
,包括A.hpp
在B.cpp
,即去只有头。 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
.我认为应该有更好的解决方案,即在 python 中我可以
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.创建另一个头文件,例如
common.hpp
并在该头文件中声明My_Func()
的函数定义。
Then, create another cpp file, common.cpp
and implement the function inside there.然后,创建另一个 cpp 文件,
common.cpp
并在其中实现该功能。
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
.现在,如果您在
A.cpp
和common.hpp
中都A.cpp
B.cpp
,则调用My_Func()
将适用于A.cpp
和B.cpp
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.