我应该在C ++中分开cpp和h文件吗? [英] Should I separate cpp and h file in C++?

查看:202
本文介绍了我应该在C ++中分开cpp和h文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的C ++程序中调用了一个模板:

I have called a template in my C++ program:

const matrix::CMatrix<double> M1(3,3,{{5.0,0.0,2.0},{1.0,1.0,3.0},{6.0,7.0,7.0}});

我遇到了这样的链接器错误:

i got such linker error:

tests.h:15: undefined reference to `matrix::CMatrix<double>::CMatrix(int, int, std::vector<std::vector<double, std::allocator<double> >, std::allocator<std::vector<double, std::allocator<double> > > >)'

经过大量搜索之后,我终于意识到这是因为我已经分离了h和cpp文件,而template却不容许它.在C语言中,建议将c和h文件分开并使用Makefile.但是根据c ++中的此类问题,是否仍建议将cpp和h文件分开?在h文件中实现某些模板以及在cpp文件中实现某些其他功能的方法不是一种干净的方法.我该怎么办?

after massive search, finally i realized it is because i have separated my h and cpp files and template does not tolerate it. In C it is suggested to separate c and h files and using Makefile. But according to such problems in c++ is it still suggested to separate cpp and h files? It is not clean way to implement some templates in h files and some other functions in cpp file. what should i do?

matrix.h

template<typename T>
class CMatrix
{
.....

matrix.cpp

matrix.cpp

implementation of CMatrix

main.cpp

defining M1

推荐答案

是的,您应该将CPP与.h文件分开.
这不仅仅是一个建议.

Yes you should separate CPP from .h files.
This is more than a suggestion.

.cpp文件被编译成编译单元,这意味着每个.cpp文件都将包含其所有代码以及包含的所有代码编译成.obj文件.

The .cpp files are compiled into compilation units, which means every .cpp file gets compiled into an .obj file with all the code it has, and all the code it includes.

因此,如果许多.cpp文件中包含.h文件中的某些代码,则它将多次编译.

So if you have some code in a .h file that is included in many .cpp files, it gets compiled many times.

现在,当您有多个项目和库时,这个事实可能会变得很难看.

Now this fact can get ugly when you have multiple projects and libraries.

无论如何,模板是一个不同的问题.
模板cals直到被实例化才真正编译(直到您使用它们).
然后,编译器为正确的类型创建所需的代码.
它不仅会在编译器第一次看到模板代码(例如常规"代码)时得到编译

Anyway, templates are a different issue.
The template calsses don't really get compiled until they are instantiated (until you use them).
Then the compiler creates the needed code for the right type.
It does not just get compiled the first time the compliler sees the templated code (like "regular" code)

因此,您需要在头文件中包含该模板化的代码,以便编译器在使用它的每个编译单元(.cpp)文件中查看"该代码. 因此,编译器可以在需要的地方创建正确的代码.

So, you need to have that templated code in a header file, so the compiler "sees" it in every compilation unit (.cpp) file that uses it.
So the compiler can create the right code where it is needed.

这篇关于我应该在C ++中分开cpp和h文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆