What are the advantages of having declarations in a .inl file? When would I need to use the same?
.inl files are never mandatory and have no special significance to the compiler. It's just a way of structuring your code that provides a hint to the humans that might read it.
I use .inl files in two cases:
For definitions of inline functions.
For definitions of function templates.
In both cases, I put the declarations of the functions in a header file, which is included by other files, then I #include the .inl file at the bottom of the header file.
I like it because it separates the interface from the implementation and makes the header file a little easier to read. If you care about the implementation details, you can open the .inl file and read it. If you don't, you don't have to.
Nick Meyer is right: The compiler doesn't care about the extension of the file you're including, so things like ".h", ".hpp", ".hxx", ".hh", ".inl", ".inc", etc. are a simple convention, to make it clear what the files is supposed to contain.
The best example is the STL header files which have no extension whatsoever.
Usually, ".inl" files do contain inline code (hence the ".inl" extension).
Those files ".inl" files are a necessity when you have a dependency cycle between header code.
For example:
// A.hpp
struct A
{
void doSomethingElse()
{
// Etc.
}
void doSomething(B & b)
{
b.doSomethingElse() ;
}
} ;
And:
// B.hpp
struct B
{
void doSomethingElse()
{
// Etc.
}
void doSomething(A & a)
{
a.doSomethingElse() ;
}
} ;
There's no way you'll have it compile, including using forward declaration.
The solution is then to break down definition and implementation into two kind of header files:
hpp for header declaration/definition
inl for header implementation
Which breaks down into the following example:
// A.hpp
struct B ;
struct A
{
void doSomethingElse() ;
void doSomething(B & b) ;
} ;
And:
// A.inl
#include <A.hpp>
#include <B.hpp>
inline void A::doSomethingElse()
{
// Etc.
}
inline void A::doSomething(B & b)
{
b.doSomethingElse() ;
}
And:
// B.hpp
struct A ;
struct B
{
void doSomethingElse() ;
void doSomething(A & a) ;
} ;
And:
// B.INL
#include <B.hpp>
#include <A.hpp>
inline void B::doSomethingElse()
{
// Etc.
}
inline void B::doSomething(A & a)
{
a.doSomethingElse() ;
}
This way, you can include whatever ".inl" file you need in your own source, and it will work.
Again, the suffix names of included files are not really important, only their uses.
Since nobody else has mentioned it:
The use of .inl files to store your inline functions can be useful for speeding up compiles.
If you only include the declarations (.h) where you need declarations, and only include inline implementations (.inl) where you need them ( i.e. probably only in .cpp and other .inl files, not .h's ), it can have a beneficial effect on your header dependencies.
This can be a significant win on larger projects with many interacting classes.
In my experience, .inl files are used to define inline functions. When they're in an .inl file, the file can be included in a header to get inline functions and in a .c file to get regular function definitions.
This way the same source can more easily work with compilers that do not have inline function supportas well as compilers that do.
They're usually used with straight C code, not often with C++ code as all C++ compilers support inline functions.
I believe it's just a naming convention for a "header" file includes inline code.
it's so that .h files can contain definitions and .inl files contain inline code which is necessary for templates.
I don't belive there is anything more to it than an naming convention to make the purpose of the file clear
Related
I have a function that is the same across all my header files and main.cpp if I define it in main.cpp will they all be able to use it once they are included or will they have a compiler issue?
Still new to this whole header file business. Thanks in advance.
In the header file (myfunction.h), you need to have only declaration of the function:
int foo(int param);
In the main.cpp (or any other cpp file - better choice would be myfunction.cpp - just make sure definition is included in exactly one file!) file, you need to have definition of the function:
int foo(int param)
{
return 1;
}
In all other source (cpp) files where you're using function foo, just include myfunction.h and use function:
#include "myfunction.h"
void someotherfunction()
{
std::cout << foo(1) << std::endl;
}
Compiler only needs to see declaration of the function before it is used. Linker will connect definition of the function with the places you've used the function. If you forget to write definition in main.cpp file, you will not get compiler, but a linker error. It may be worth of mentioning that compiler is compiling each cpp file separately, and linker's job is to combine all compiler object files and to produce final output file. On most setups, linker will be called automatically after compiling, so you may not be familiar with it.
If you include entire function definition in the header file, that definition will be compiled in each translation unit where header file is included, and you will get multiple symbol definition linker error, or something similar - that's why you need to include only declaration of the function inside header file. However, there are exceptions for this - for example, you may declare your function inline - other answers explain this approach.
So, now myfunction.h contains the function declaration:
#ifndef MY_FUNCTION_H
#define MY_FUNCITON_H
// declaration
int myfunction();
#end if
myfunction.cpp contains the function definition:
int myfunction()
{
return 4;
}
Now, in file1.cpp and in file2.cpp you want to use this function, so you're including myfunction.h:
// file1.cpp
#include "myfunction.h"
// somewhere in the file
void foo()
{
std::cout << myfunction();
}
... and in the second file:
// file2.cpp
#include "myfunction.h"
// somewhere in the file
void bar()
{
/// ...
std::cout << myfunction();
}
Header files in C and C++ are a language artifact. They are the consequence of the fact, that C and C++ can be implemented as a single-pass compiler. In contrast, Pascal - for example - has a two-pass compiler, that skips over unknown entities during the first pass, and fills in the missing bits in a second pass. Consequently, in C and C++ every type, object, and method must be declared before it can be used. This is the main responsibility of header files.
Header files are expanded into any file that includes them. In other words: The preprocessor replaces the statement #include "foo.h" with the contents of the file "foo.h". With this being the case you need to be careful to not violate the single definition rule: An entity must not be defined more than once.
To meet both requirements you have two options: Declare and define the function in the header, using the inline keyword, or declaring it in the header only, and defining it in another compilation unit.
The following code illustrates both solutions:
// foo.h
inline void foo() {
// Method is implemented in this header file.
// It is marked 'inline' to prevent linker errors
// concerning multiply defined symbols.
...
}
Delaration in header only, implementation in another compilation unit:
// foo.h
extern void foo();
// foo.cpp (or another compilation unit)
void foo() {
...
}
Regardless of which solution you go with, you can use foo() from any compilation unit. If you want to use it from "main.cpp" the code would look something like this:
// main.cpp
#include "foo.h"
int main() {
foo();
}
So you have a function which is used in all your header files, why don't you make a utility.h which keeps track of these types of functions and inline the functions in the .h ?
Declare the function prototype in a custom header file:
int add(int a, int b);
let say header file name is myfunction.h and include it wherever you need the function.
now you can define a function on another.cpp or main.cpp
int add(int a, int b){
return a+b;
}
include your custom header file like this:
#include "myfunction.h"
remember your main.cpp and other cpp files and the new header file should be in the same path.
If you have two files:
main.cpp
#include "func.h"
int main(){
hello();
std::cout<<" world!\n";
return 0;
}
& func.h
#ifndef FUNC_H
#define FUNC_H
#include <iostream>
void hello(void){
std::cout<<"hello";
}
#endif
iostreams objects and functions e.t.c will work fine from within main.cpp.
This posts answers sum up #ifndef pretty well if you would like to know more.
I'm using multiple C++ files in one project for the first time. Both have need to include a protected (#ifndef) header file. However, when I do that, I get a multiple definition error.
What I have is two one .cpp file that calls the header directly, and one indirectly (Another include includes it) and then two other header files that include it.
So what do I need to do to get rid of the error?
ERROR:
obj\Debug\main.o||In function Z14sortLibQtyTest4BookS_':|
[PATH]\miscFuncs.h|16|multiple definition ofsortLibQtyTest(Book, Book)'
CODE:
bool sortLibQtyTest(Book a, Book b){ return a.getQty() > b.getQty(); }
It should be mentioned that this isn't the only function giving me problems, probably more than ten are, and some aren't so short and sweet. Also, the functions are needed in multiple files.
You have two options to solve this multiple definition problem: Mark the method inline, or put the definition in a .cpp file.
1) Mark the method inline:
// Foo.h
inline bool foo(int i) { return i = 42; }
2) Put the definition in a .cpp file:
// Foo.h
inline bool foo(int i); // declaration
// Foo.cpp
bool foo(int i) { return i = 42; } // definition
Whether the method is actually inlined by the compiler in the first case is irrelevant here: inline allows you to define a non-member function in a header file without breaking the one definition rule.
The ".cpp" and ".h" suffixes are largely a matter of convention. As far as the compiler is concerned, where a line of code came from is irrelevant. When you #include that function into your .cpp files, you are implementing that function in that .cpp file.
So when the compiler is done and it asks the linker to knit together the code from your two cpp files, it finds a conflict: two functions with the same name and fingerprint (arguments and return). This is an error.
You need to either:
a. Put the implementation in one source file, and just leave a prototype declaration in the header
// .h
extern bool sortLibQtyTest(Book a, Book b);
// file1.cpp
bool sortLibQtyTest(Book a, Book b) { /* implementation */ }
b. Mark the function as inline: when you call the function, the compiler will insert copies of the function body as needed which can be wasteful, but often times the compiler can figure out the efficient thing to do.
inline bool sortLibQtyTest(Book a, Book b) { return a.getQty() < b.getQty(); }
c. Mark the function as "static" which tells the compiler to create a copy of the function for every source file that includes it, but not to expose it to the linker. If some source files include the header without using the function, the compiler has to detect this and remove it - which not all compilers/optimization levels do, so it can be doubly wasteful.
static bool sortLibQtyTest(Book a, Book b) {return a.getQty() < b.getQty(); }
d. Avoid the downsides of c, mark it static inline
static inline bool sortLibQtyTest(Book a, Book b) { return a.getQty() < b.getQty(); }
If the Line you quoted after "CODE" is in a header file you can either:
add inline to the definition or
remove the function body from the header and put it into 1 (and only 1) of your source files.
I've read a lot for this problem ,but I haven't found a proper solution.
So i have 4 files:
includes.h - which contains all libraries I need in other files + some global functions
cities.h - which contains declarations of 2 classes
cities.cpp - which contains definitions of the 2 classes in cities.h
source.cpp - where is the main functon
And I have(and need) these includes
//cities.h
#include "includes.h"
//cities.cpp
#include "cities.h"
//source.cpp
#include "cities.h"
I've tried almost all combinations of #ifndef in all of the files and the program continues to give me the same error: function_X already declared in cities.obj.And this error repeats for all functions in "includes.h".
Please help me.This makes me a lot of headaches.
As you've described in the comments, you have function definitions in your includes.h header file. When this is included in multiple implementation files, you end up with multiple definitions of those functions in your program. This breaks the one definition rule. You should simply declare functions in includes.h and move their definitions into a includes.cpp file.
Something like this:
// includes.h
void foo();
int bar(int);
// includes.cpp
void foo() {
// implementation
}
int bar(int x) {
// implementation
}
I'm going to try and preempt a question that typically follows this answer. No, your include guards (#ifndef ...) are not meant to prevent this. They only prevent a header being included multiple times in a single translation unit. You are including the header in multiple translation units, which an include guard does not stop.
On top of what #sftrabbit said, If you are making a headers only library where you need to define the functions in the the header file this is possible with the keyword inline.
// includes.h
inline void foo() {
// implementation
}
inline int bar(int x) {
// implementation
}
This use of inline is not to be mistaken with its other use as a compiler suggestion to inline the function call.
I began to write my program in a single cpp-file but now I have too much code so I decided to separate it. But the problem is that I have many constants, includes and some other things that I want to have all in one place. Unfortunately, all of them are needed by dependent parts of code so I can't do it with usual include files.
What would help me?
(I write under Linux and compile with command-line)
(Sorry for my English :))
As Hristo said, you should generally write the definitions in header files and write the implementation in the source code files.
To answer your question however:
But the problem is that I have many constants, includes and some other things that I want to have all in one place.
What I've typically done is create a single file called something like "common.h" or "defs.h" (I took the idea from Doom...) and that file has many defines that you find you need throughout your entire program. If you are using constants, declare the constants in the header file like so:
extern const int MAX_SOMETHING;
extern const bool TRUTH_VALUE;
and make a complementary source file (defs.cpp or common.cpp) that defines these constants:
const int MAX_SOMETHING = 5;
const bool TRUTH_VALUE = true;
so now when you include the common/defs.h in other source files, the extern keyword will tell that source file that the definition is in another source file (its in the common/defs.cpp) so it will find the definition in there, and you can use it anywhere where you have included common/defs.cpp.
In most projects definitions are in header files and implementations are in source code files. However the implementations of template functions must be in the header files because they must be visible to all source files using them. Variables should be defined extern in header files and be declared in source files. Constants may also be declared in header files static.
Example:
Foo.h
#pragma once
class Foo{
public:
void bar();
template<class Type>
void increment(Type &a){
++a;
return;
}
};
extern Foo theFoo;
static const int five=5;
Foo.cpp
#include "Foo.h"
#include <iostream>
void Foo::bar(){
std::cout<<"Foo::bar called"<<std::endl;
return;
}
Foo theFoo;
Main.cpp
#include "Foo.h"
#include <iostream>
int main(){
theFoo.bar();
std::cout<<five<<std::endl;
return 0;
}
I am using boost msm library (you don't need to know how it works) to code my statemachine, and i have a cpp source file organization question.
in the first source file (1.cpp) I define the statemachine, the event and the actions and the transition table, but I would like to define the state in another cpp file just because I would need to edit the states much more often then anything else in the statemachine.
Now what I did is that I wrote the states in another source file (2.cpp) and I included 2.cpp in 1.cpp
It compiles and everything, but its not clean at all, Id like to encapsulate this somehow..Any ideas?
Well typically you would include only .h files, i.e., the header files that declare types and the functions that you will implement in your associated .cpp file. You should not need to include an implementation file at all. Have you created any header files? Here is a basic example:
// Foo.h
class Foo {
// note that it is not defined here, only declared
public void some_function(int i);
};
// Foo.cpp
#include "Foo.h"
#include <iostream>
// implement the function here
void Foo::some_func(int i) {
std::cout << i;
}
Typically in C++ the definitions of classes and the function prototypes exist in header files (ending in .h or .hpp), with the implementation of functions existing in source files (ending in .cpp or .cxx). This allows you to expose an external interface so that other files can use the definitions used in the first file. You would make function prototypes and class declarations in your header file, and then include that header file in both cpp files.
In general, it is good practice to only include header files, and not include source files in other files.
If i were to write this from scratch (a finite state machine),
i will put following inside:
fsm.h:
struct fsm_rule {
/* state to which this rule belongs to */
int state;
/* new state */
int next;
/* is called when rule matches */
int (*fn)(int in, void *ctx);
};
struct fsm_state {
int nrules;
struct fsm_rule *rules;
};
struct fsm {
int nstates;
struct fsm_state *states;
};
and then inside fsm.c i will go ahead and implement required methods.
PS: Ofcouse fsm.c includes fsm.h