I have a very small function that could be a macro, but anyway, I thought inline function would do exactly the same.
But nah, when I mark a function in a namespace as inline it is not visible by any other file that includes my module.
I tried it both with a static class and a namespace. No error when the function is declared or implemented, error in each reference, exactly as if the function was static.
Is there a way to have an inline function available for other files that include the file where my function is declared?
Let's say I have a module that handles some hardware stuff, and one of the functions is something like this:
bool getState(HWFlag flag)
{
return (State & flag) > 0
}
I know, it can be written as macro, but logically the function is a part of a bigger module. I would certainly used a macro in C, but it's C++ so I thought there might be a better way. But well, I obviously don't understand how it works.
BTW, shouldn't the compiler just inline it anyway so I shouldn't even care?
BTW2: Is making the module that mainly talks with C code a class with only static method a bad idea or does it have any use? That's how I made it initially but later decided to just make it a namespace to simplify the syntax a little. But in any case, if I use the inline keyword the function becomes private.
An inline function should be defined identically in every translation unit that uses it. So you should define your inline function exactly as you would a macro--in a header file that gets included by all of the files that need it.
Related
I have a static constexpr member function that i declare in the .h file. If i define the function right away in the header file, everything works perfectly. I have the general inclination to define functions in the .cpp file (even if i want them inlined, i would use the inline keyword and again do so) so i when i try to do it, it seems okay at first but when i try to call this function i get the following error:
static constexpr uint16_t ClassA::myFoo()' used before its definition
I would like learn if there is a way to define a static constexpr member function in the .cpp file rather than the header. If thats not possible or maybe limited due the compiler i am using, is there any side effects defining the function in the .h file ? (I know it is explicitly inline for normal functions but i am not sure for a constexper static function).
PS: I am using arm-none-eabi-g++ (c++17) and Clion for a small embedded project.
I would like learn if there is a way to define a static constexpr member function in the .cpp file rather than the header.
Yes... but you must define the function in every TU where it is used because it is an inline function. As such, it is simpler to put the definition into a header so that same definition will be included into all the TUs that need it.
It is an inline function because constexpr functions are implicitly inline functions - i.e. whether or not you use the inline keyword.
is there any side effects defining the function in the .h file ?
The effect of doing this is that the function definition will be included into every TU that include the header. I don't quite understand what you mean by "side" effect in this context.
Suppose i have a header that should work in both C and C++.
This header contains some functions that the program must define, such as:
EXPORTED void * STD_API GetSymbol(CProject * p, char * s);
How can i ensure that these functions are actually defined somewhere? Even if the project actually compiles without, it is invalid because these functions will be looked up at runtime by another module (it is to be compiled as a module/dll/dylib/whatever).
The only thing i can think of is to use the definition somewhere, perhaps in a function call. However, that requires a function implementation in the header, which we all know will lead to multiple defintions.
In C++ you can probably get away with a hack like this:
#ifdef __cplusplus
static inline void _impcheck()
{
assert(0 && "_impcheck called.");
GetSymbol(NULL, NULL);
}
#endif
(because of how inline modifer allows multiple definitions). But how about c?
Firstly, C has static and inline too.
Second, how about...
documenting that the functions are to be implemented by the user?
checking at runtime the availability of the functions and reporting an error/throwing an exception when one can't be found? dlsym() (I assume you are using the dlopen() API, is that true?) will return a null pointer when it can't find a symbol.
If you really want a link-time failure, then you can try using the functions (call them, or assign their names to volatile function pointers if you don't want side effects to be performed prematurely, etc.)
C allows exactly the same static inline function. But the compiler will probably optimize it away because your assert gets triggered so that following code is marked unreachable.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Inline functions in C++
What does the compiler do if I completely implement a class in its header file? A typical example follows:
class MyException
{
public:
explicit MyException(const char* file, int line) file(file), line(line) {};
const char* getFile() const { return file };
int getLine() const { return line };
private:
const char* const file;
const int line;
};
My intention is to use the class like this: throw MyException(__FILE__, __LINE__).
I include this header file into each .cpp file. I suppose the compiler will compile the class as many times as it is defined and include the (identical) machine code into every object file it produces. Now, what will the linker do? I tried a simpler example (without all those pesky const's) and it compiled fine.
What would happen, if instead of a simple class, I implemented a three-screenful-long C function in a header file? And the final question, should I split my example into .h and .cpp files?
All methods will be inline methods. You may loose some minimal time on the overall compilation, but it's ok. As far as I know the only problem that can occur is if you have a static non-cost member variable. Then you have to assign a storage place for it (place a definition and and initial value if you want) presumably in a .cpp or else you will get linker errors about multiple definition.
I've seen header-only projects which had only the main() function in a CPP, but that was heavily templated.
Update for C++17: You can declare static non-const members as inline in your header file since C++17. This makes header-only libraries easily possible without gymnastics like static variables inside inline functions.
A class definition itself doesn't produce any code. It just shows users of the class how it is layed out, so they can generate appropriate code to manipulate it.
It's the member functions of the class that generate code. When you define a member function inside the class definition it gives the function an implicit inline declaration.
A function call can be compiled and linked in one of two ways:
(1) A single copy of the function code with a RETURN assembly instruction at the end can be placed in the image, and a CALL assembly instruction can be placed (along with param passing and return value transfer) at the call site to transfer control to this code.
or
(2) An entire copy of the function implementation can replace the entire function call at the call site.
A function declared inline is a recommendation to the compiler to do it the second way. Further an inline declaration allows the function to be defined in several translation units (so it can be placed in a shared header file). In order for the compiler have the option of implementing the second method, it needs a copy of the function implementation at compile-time. This isn't available if the function implementation is in a foreign translation unit.
It should also be noted that modern compilers do complicated things with functions declared inline. See:
http://gcc.gnu.org/onlinedocs/gcc/Inline.html
When you implement member functions inside a header file, all those functions become implicitly inline.
What does this mean and what implications does it have?
As per,
C++03 Standard ยง7.1.3/4:
It hints the compiler that substitution of function body at the point of call is preferable over the usual function call mechanism.
Even if the inline substitution is omitted, the other rules(especially w.r.t One Definition Rule) for inline are followed.
So Yes, every translation unit will have the definition of the inline function.This may result in increase in the size of your binaries.
Usually any good mainstream compiler will substitute function body at the point of call if needed, so marking functions inline merely for #1 is not really a good idea but if you want to make your intent clear to users of your class then you can do so by defining the functions within the header or explicitly marking your functions as inline.
Should I split my example into .h and .cpp files?
Yes, that is the usual compilation model that most of the projects use, wherein you separate the interface(.h) from the implementation(.cpp).The interfaces are shared with the users of your code as header files while the implementation is provided in the form of binaries.To some extent this provides a safeguard to your intellectual property.
This is known as the Separation Model.
C++ projects using templates will usually use the Inclusion Model rather than the Separation Model of usual C++ projects.
I know what it means when static function is declared in source file. I am reading some code, found that static function in header files could be invoke in other files.
Is the function defined in the header file? So that the actual code is given directly in the function, like this:
static int addTwo(int x)
{
return x + 2;
}
Then that's just a way of providing a useful function to many different C files. Each C file that includes the header will get its own definition that it can call. This of course wastes memory, and is (in my opinion) a quite ugly thing to be doing, since having executable code in a header is generally not a good idea.
Remember that #include:ing a header basically just pastes the contents of the header (and any other headers included by it) into the C file as seen by the compiler. The compiler never knows that the one particular function definition came from a header file.
UPDATE: In many cases, it's actually a good idea to do something like the above, and I realize my answer sounds very black-and-white about this which is kind of oversimplifying things a bit. For instance, code that models (or just uses) intrinsic functions can be expressed like the above, and with an explicit inline keyword even:
static inline int addTwo(int *x)
{
__add_two_superquickly(x);
}
Here, the __add_two_superquickly() function is a fictional intrinsic, and since we want the entire function to basically compile down to a single instruction, we really want it to be inlined. Still, the above is cleaner than using a macro.
The advantage over just using the intrinsic directly is of course that wrapping it in another layer of abstraction makes it possible to build the code on compilers lacking that particular intrinsic, by providing an alternate implementation and picking the right one depending on which compiler is being used.
It will effectively create a separate static function with the same name inside every cpp file it is included into. The same applies to global variables.
As others are saying, it has exactly the same meaning as a static function in the .c file itself. This is because there is no semantic difference between .c and .h files; there is only the compilation unit made up of the file actually passed to the compiler (usually named .c) with the contents of any and all files named in #include lines (usually named .h) inserted into the stream as they are seen by the preprocessor.
The convention that the C source is in a file named .c and public declarations are in files named .h is only a convention. But it is generally a good one. Under that convention, the only things that should appear in .h files are declarations so that you generally avoid having the same symbol defined more than once in a single program.
In this particular case, the static keyword makes the symbol be private to the module, so there isn't a multiple-definition conflict waiting to cause trouble. So in that one sense, it is safe to do. But in the absence of a guarantee that the function would be inlined, you take the risk that the function would be instantiated in every module that happened to #include that header file which at best is a waste of memory in the code segment.
I am not certain of what use cases would justify doing this at all in a generally available public header.
If the .h file is generated code and only included in a single .c file, then I would personally name the file something other than .h to emphasize that it isn't actually a public header at all. For example, a utility that converts a binary file into an initialized variable definition might write a file that is intended to be used via #include and could very well contain a static declaration of the variable, and possibly even static definitions of accessor or other related utility functions.
If you define the function in a header file (not simply declare it), a copy of the function will be generated in each translation unit (basically in each cpp file which includes this header).
This may increase the size of your executable, but this may be negligible if the function is small. The advantage is that the most compilers may inline the function, which may increase the code performance.
But there may be a big difference in doing this which wasn't mentioned in any answer. If your function uses a static local variable such as:
static int counter()
{
static int ctr = 0;
return ctr++;
}
Rather than:
//header
int counter();
//source
int counter()
{
static int ctr = 0;
return ctr++;
}
Then each source file including this header will have its own counter. If the function is declared inside the header, and defined in a source file, then the counter will be shared across your whole program.
So saying that the only difference will be performance and code size is wrong.
There is not semantic difference in defining in source file or header file, basically both means the same in plain C when using static keyword that, you are limiting the scope.
However, there is a problem in writing this in header file, this is because every time you include the header in a source file you'll have a copy of the function with same implementation which is much similar to have a normal function defined in header file. By adding the definition in header you are not achieving the what the static function is meant for.
Therefore, I suggest you should have your implementation only in your source file and not in header.
It is usefull in some "header-only" libraries with small inline functions. In a such case you always want to make a copy of the function so this is not a bad pattern. However, this gives you an easy way to insert separate interface and implementation parts in the single header file:
// header.h
// interface part (for user?!)
static inline float av(float a, float b);
// implementation part (for developer)
static inline float av(float a, float b)
{
return (a+b)/2.f;
}
Apple vector math library in GLK framework uses such constuction (e.g. GLKMatrix4.h).
I am thinking it is a best practice to declare them as static, as it makes them invisible outside of the module.
What are your thoughts on this?
For C++, a better than static is to put it in an unnamed (anonymous) namespace. This is the preferred way to prevent pollution of the Global namespace.
namespace {
void myLocalFunction() {
// stuff
}
}
If it is truly an function which is internal only to that .c file, then yes. It should help avoid polluting the global namespace. Also, I think that the compiler is able to do some optimizations with calling conventions if the function is static since it knowns no other source file needs to know how to call it. This only really applies to c because as others have noted, c++ has namespaces to address this issue.
There was a lot about implementation details and not too much about concept.
Limiting the scope of variable/function etc.. is a good practice indeed. This is a basic concept of object oriented design - you want keep private as private. This way your interface is cleaner and code maintenance is easier. And you will not find one day that changing something that you considered as private broke compilation because somebody in another part of project liked your function and decided to use it.
In C, I make everything - functions and variables - static at file scope until I can demonstrate they're necessary outside the file. I'll make things static within a function if only that function will use them and they are not too huge. Basically, if the declaration is bigger than the rest of the function, I may put the declaration outside the function. And, of course, there's a header for the public services provided by a source file.
Agreed. As a consequence, the prototypes for the static functions must go at the top of the .c file, not in the .h file.
In C++, you should use an anonymous namespace, like so:
// foo.cpp
namespace
{
class Core { ... };
void InternalFandango(Core *);
}
void SomeGloballyVisibleFunction()
{
InternalFandango(&core);
}
Advantage: this is applicable to struct / class declarations, too.
In C, just mark the functions "static". There's nothing against using "static" in C++, too, but I've learnt to prefer the namespace, as it is one single concept that works for all declarations.
I think C and C++ have different constraints concerning static: in C you don't have namespaces and .c files are your modules, so it is really really important to put all non-public functions as static to prevent errors!
About the only potentially useful property I can think of for this use of "static" in C++, that anonymous namespaces don't provide, is that there's a warning in GCC you can switch on for unused static functions (a form of dead code). You don't get that for unused functions in anonymous namespaces, so in the unlikely event that you want the compiler to tell you when you stop using the function, do it that way.
In C code, make your functions static by default. Only make non-static functions and .h declarations for functions that will be needed by other modules.
In C++ code, put those functions that are local to the file into an anonymous namespace and make them static. In the GNU compiler at least, this will result in the best and smallest code, because no function will be written if all uses are inlined. If you intend it to be inlined, then of course marking it inline is even better than static.
I do not know why g++ writes the uncalled function bodies that are in anonymous namespaces into the output at all, but it does. Functions with hidden visibility seem to show up as well; marked as hidden symbols, but still producing unused code blocks in the object file. GCC probably doesn't understand that the code isn't needed in those cases. Or I am missing something, always possible.
If you're using GCC, then you should take a look at the visibility flag (see http://gcc.gnu.org/wiki/Visibility for a full discussion).
It'll hide symbols completely as opposed to marking them unreachable. That reduces the symbol table, and helps decrease link times.
Not only that, it opens the door for more inlining, if that's what you're after.
If by 'module' you just mean a CPP file, you could just place the declaration and the definition right in the CPP file.
In C++, you'd declare the function private like this:
class MyClass
{
public:
void publiclyAccessibleFunction();
private:
void onlyAccesibleFromWithinTheClass();
int some_member_parameter;
};
Note the onlyAccesibleFromWithinTheClass() function.