0

I have a main.cpp and node.h(template) file. It seems to work when I compile only main.cpp that includes node.h. I am wondering if it is okay not to compile node.h?

9
  • Changed the question tag from [c] to [c++] for you, since this is obviously not C. Commented Sep 28, 2018 at 0:11
  • 1) There's no such thing as "templates" in C: you probably meant C++, 2) #include "implementation.hpp in a .h header is generally a Bad Idea. Don't do it. Commented Sep 28, 2018 at 0:13
  • Unable to reproduce with the MCVE (minimal reproducible example) I hacked out, which means I'm doing something different from what you did. If you can produce your own MCVE either you'll see what you did wrong while making the MCVE or you'll have something we can use to duplicate what you are doing and be in a much better position to help you. Commented Sep 28, 2018 at 0:30
  • Which file are you including from other code? The first or the second header file? Commented Sep 28, 2018 at 0:34
  • sorry for the confusion, i meant C++ not C Commented Sep 28, 2018 at 0:40

1 Answer 1

2

C++ compilers generally require that the definitions of all templates be visible in every translation unit in which they are used (the one real exception is if you only allow particular specializations to be used and those specializations are instantiated somewhere, in that particular instance you can get away with hiding the implementation).

Whether you split template declarations from their definitions as you describe is really just a matter of style. Personally I don't care for that as it makes it that much harder to find the actual code for any given template.

However if the code you are dealing with is large enough (as many boost libraries are, for example), then it may well make sense to implement the public template in terms of many private parts and it can well make sense to have those parts be split into their own headers. But again, so long as all the needed code is available in every translation unit it is simply style and one choice is really not any "better" than another so long as it is consistent.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.