简体   繁体   English

使用 main() 包含来自其他 cpp(hpp) 文件的函数

[英]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.hppB.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.cppcommon.hpp中都A.cpp B.cpp ,则调用My_Func()将适用于A.cppB.cpp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当有 hpp 时,我可以在 main 中包含一个 cpp 文件吗? - Can I include a cpp file in the main when there is a hpp? 将函数及其实现从主文件移动到不同的文件(.hpp 和 .cpp)时,性能会受到很大影响 - When moving a function and it's implementation to a different file (.hpp and .cpp) from the main file, performance greatly suffers 有什么方法可以从.hpp 文件中检查相应的.cpp 文件中是否使用了 C stdio 函数? - Is there any way to check, from a .hpp file, if C stdio functions are used in the corresponding .cpp file? 如何在CMakeLists.txt中包含h / hpp头文件,而不是cpp或其他hpp文件 - How to include h/hpp header files in CMakeLists.txt instead of cpp or other hpp files Main.cpp无法访问头文件和其他.cpp文件中的变量和函数 - Main.cpp can't access variables and functions in header file and other .cpp file 使用模板类时,除main.cpp之外似乎不包含任何cpp文件 - Can't seem to include any cpp file other than main.cpp when using template class 从 main.cpp 中的另一个文件调用函数 - calling functions from another file in main.cpp 如何从实现中提取声明(.hpp文件)(.cpp文件)? - How to extract declarations (a .hpp file) from implementation (a .cpp file)? Visual Studio 包含来自其他项目的 cpp 文件 - Visual Studio Include cpp file from other project .hpp和.cpp文件中的常量数组 - Const array in .hpp and .cpp file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM