I am defining data structures for a project. i have some simple implementation that i want in my header because i don't want to break it up into separate files. Is this illegal or bad practice or what?
I am defining data structures for a project. i have some simple implementation that i want in my header because i don't want to break it up into separate files. Is this illegal or bad practice or what?
> Is having implementation in headers illegal, or just bad practice?
It's best to avoid it if you can, but not illegal.
-Prelude
well i guess it is illegal, i am too quick to make a post before actually trying something myself.
template functions can be a good idea to put in a header. Most compilers cannot handle the export keyword, which makes template functions in source files possible.
It can cause your link to fail as multiple definitions of the functions you define will exist in more than 1 module.....
You can use the keyword "static" to give your function internal linkage (relative only to the module that uses it)...but that is deprecated and these days you should just include the function in an empty namespace
Code://main.cpp
#include "temp.h"
int main(){
foo();
bar();
}
Code://module.cpp
#include "temp.h"
void foo(){bar();}//definition of foo (in cpp file)
Code://temp.h
#include <iostream>
void foo();//forward declaration for foo
namespace{//empty namespace
void bar(){//definition of foo (in h file)
std::cout << "Foobar" << std::endl;
}
}
inline functions in the header are fine though.
I would only use an inline in the header when you intend to make a function inline for speed reasons. inline is after all something of a glorified macro.
I'm not sure, but I've once heard that if you define a function in the header file, it's automaticaly inlined...So is that true?
You mean anonymous namespace fordy not empty namespace.
There is never any reason to include code in a header file. If you must inline then specify with inline and let compiler decide what to do and put the implementation in a .cpp file and keep your headers for declarations only.
stoned, that's good practice so long as the inline function is used in the module where it's defined. you can't use an inline function in another module however.
edit: Module == cpp file just to clarify
LOL...yup....your right...Quote:
Originally posted by Stoned_Coder
You mean anonymous namespace fordy not empty namespace.