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).
Related
I have what seems a relatively simple question, but one that keeps defying my efforts to understand it.
I apologise if it is a simple question, but like many simple questions, I can't seem to find a solid explanation anywhere.
With the below code:
/*foo.c*/
#include "bar.h"
int main() {
return(my_function(1,2));
}
/*bar.h*/
int my_function(int,int);
/*bar.c*/
#include "bar.h" /*is this necessary!?*/
int my_function(int x, int y) {
return(x+y);
}
Simply, is the second inclusion necessary? I don't understand why I keep seeing headers included in both source files. Surely if the function is declared in "foo.c" by including "bar.h," it does not need to be declared a second time in another linked source file (especially the one which actually defines it)??? A friend tried to explain to me that it didn't really matter for functions, but it did for structs, something which still eludes me! Help!
Is it simply for clarity, so that programmers can see which functions are being used externally?
I just don't get it!
Thanks!
In this particular case, it's unnecessary for the reason you described. It might be useful in situations where you have a more complex set of functions that might all depend on each other. If you include the header at the top of the .cpp file, you have effectively forward-declared every single function and so you don't have to worry about making sure your function definitions are in a certain order.
I also find that it clearly shows that these function definitions correspond to those declarations. This makes it easier for the reader to find how translation units depend on each other. Of course, the names of the files might be sufficient, but some more complex projects do not have one-to-one relationship between .cpp files and .h files. Sometimes headers are broken up into multiple parts, or many implementation files will have their external functions declared in a single header (common for large modules).
Really, all inclusions are unnecessary. You can always, after all, just duplicate the declarations (or definitions, in the case of classes) across all of the files that require them. We use the preprocessor to simplify this task and reduce the amount of redundant code. It's easier to stick to a pattern of always including the corresponding header because it will always work, rather than have to check each file every time you edit them and determine if the inclusion is necessary or not.
The way the C language (and C++) is designed is that the compiler processes each .c file in isolation.
You typically launch your compiler (cl.exe or gcc, for example) for one of your c files, and this produces one object file (.o or .obj).
Once all your object files have been generated, you run the linker, passing it all the object files, and it will tie them together into an executable.
That's why every .c file needs to include the headers it depends on. When the compiler is processing it, it knows nothing about which other .c files you may have. All it knows is the contents of the .c file you point it to, as well as the headers it includes.
In your simplified example inclusion of "bar.h" in "bar.c" is not necessary. But in real world in most cases it would be. If you have a class declaration in "bar.h", and "bar.c" has functions of this class, the inclusion is needed. If you have any other declaration which is used in "bar.c" - being it a constant, enum, etc. - again include is needed. Because in real world it is nearly always needed, the easy rule is - include the header file in the corresponding source file always.
If the header only declares global functions, and the source file only implements them (without calling any of them) then it's not strictly necessary. But that's not usually the case; in a large program, you rarely want global functions.
If the header defines a class, then you'll need to include it in the source file in order to define member functions:
void Thing::function(int x) {
//^^^^^^^ needs class definition
}
If the header declares functions in a namespace, then it's a good idea to put the definitions outside the namespace:
void ns::function(int x) {
//^^^^ needs previous declaration
}
This will give a nice compile-time error if the parameter types don't match a previous declaration - for which you'd need to include the header. Defining the function inside its namespace
namespace ns {
void function(int x) {
// ...
}
}
will silently declare a new overload if you get the parameter types wrong.
Simple rule is this(Considering foo is a member function of some class):-
So, if some header file is declaring a function say:=
//foo.h
void foo (int x);
Compiler would need to see this declaration anywhere you have defined this function ( to make sure your definition is in line with declaration) and you are calling this function ( to make sure you have called the function with correct number and type of arguments).
That means you have to include foo.h everywhere you are making call to that function and where you are providing definition for that function.
Also if foo is a global function ( not inside any namespace ) then there is no need to include that foo.h in implementation file.
Lot of the times when I watch other people's code I see some are including a .h file and some are including a .c/.cpp file. What is the difference?
It depends on what is in the file(s).
The #include preprocessor directive simply inserts the referenced file at that point in the original file.
So what the actual compiler stage (which runs after the preprocessor) sees is the result of all that inserting.
Header files are generally designed and intended to be used via #include. Source files are not, but it sometimes makes sense. For instance when you have a C file containing just a definition and an initializer:
const uint8_t image[] = { 128, 128, 0, 0, 0, 0, ... lots more ... };
Then it makes sense to make this available to some piece of code by using #include. It's a C file since it actually defines (not just declares) a variable. Perhaps it's kept in its own file since the image is converted into C source from some other (image) format used for editing.
.h files are called header files, they should not contain any code (unless it happens to contain information about a C++ templated object). They typically contain function prototypes, typedefs, #define statements that are used by the source files that include them. .c files are the source files. They typically contain the source code implementation of the functions that were prototyped in the appropriate header file.
Source- http://cboard.cprogramming.com/c-programming/60805-difference-between-h-c-files.html
you can look at gcc website (https://gcc.gnu.org/onlinedocs/gcc/Invoking-G_002b_002b.html) that reports a good summary of all the extensions that you can use in C/C++:
C++ source files conventionally use one of the suffixes ‘.C’, ‘.cc’, ‘.cpp’, ‘.CPP’, ‘.c++’, ‘.cp’, or ‘.cxx’; C++ header files often use ‘.hh’, ‘.hpp’, ‘.H’, or (for shared template code) ‘.tcc’; and preprocessed C++ files use the suffix ‘.ii’. GCC recognizes files with these names and compiles them as C++ programs even if you call the compiler the same way as for compiling C programs (usually with the name gcc).
Including header file with declarations is the main, recommended and used almost anywhere, method for making consistent declarations among a project. Including another source file is another (very rare) kind of beast, and it's useful and possible under specific conditions:
There is a reason to split code to separate source files despite it shall be compiled as a single module. For example, there are different versions of some functions which shan't be visible from another modules. So, they are declared static but which version is included is regulated by compile options. Another variant is size and/or maintanenance credentials issues.
The included file isn't compiled by itself as a project module. So, its exported definitions aren't in conflict with the module that file is included to.
Here, I used terms definition and declaration in the manner that the following are declarations:
extern int qq;
void f(int);
#define MYDATATYPE double
and the following are definitions:
int qq; // here, the variable is allocated and exported
void f(int x) { printf("%d\n", x); } // the same for function
(Also, declarations include C++ methods with bodies declared inside their class definition.)
Anyway, the case another .c/.cxx/etc. file is included into source file are very confusing and shall be avoided until a very real need. Sometimes a specific suffix (e.g. .tpl) is used for such files, to avoid reader's confusion.
Many other questions deal with how to allocate a variable by declaring it in a header file and defining it (allocating) in a .cpp file.
What I want to do is not use any .cpp files for my class, and to define all functions as inline (in the header file). The problem that I run into is how to define static member variables so that even when the .h file is included in multiple compilation units I don't get the "first defined here" linker error.
I'm open to preprocessor hacks, etc. if it gets the job done. I just want to avoid any .cpp files.
If it matters I'm using GCC.
You can abuse the singleton pattern if you really must avoid any .cpp files:
class Foo {
public:
static Bar& getMyStatic() {
static Bar bar;
return bar;
};
};
This works because now the variable is a static variable inside a function, and static has a different meaning within a function context than within a class context. And for functions, the linker does recognize multiple identical definitions and throws away the copies.
But, of course, I would strongly advise against avoiding .cpp files: It means that you get into a situation where you have to build the entire program, or at least large parts of it, in one big piece. Every change you do will necessitate a complete rebuilt which slows down your change-compile-test cycle significantly. For very small projects that might not be a problem, but it is for medium to large ones.
With static variables you have to put in a .cpp file to avoid the possibility of multiple static variables when the intention is to have just the one. Besides it is not a good idea to have large inline methods as it is only a hint to the compiler but also makes compilation take longer (you change some of those functions in development and then lots of dependent files will need to get compiled!)
However if you do not want lots of .cpp files with just a few statics in it why not have just one file to store them in.
As long as you only include that header file once in your whole project, you'll be OK. However, that's a pretty strong requirement, and can be difficult to make others adhere to.
You could have a static variable, but that means you have more than one for the entire program, which may or may not matter (bear in mind that you can't change it in the future, so you may have what's known as a "latent bug" - you change some other code, and all of a sudden you have created a new bug, because the variable isn't ONE variable).
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).
noob question right here. How do you pass values between 2 different cpp files in the same project? Do you make objects? if yes, how does the other cpp file see it?
some enlightment pls..
EDIT: some clarifications. I'm trying to interface direct input with a program (of which I have the plugins sdk). I'm trying to interface a joystick with it. It seems that there is no main function when I look through the code, but I might be wrong (like, I might not look in the right files). I know programming, and pointers and stuff, classes. Is there anything I should learn or get into in order to achieve what I want?
In all but few cases it's a bad idea to share data among compilation units. A compilation unit, just to get you up to speed with the C++ terminology, usually effectively refers to an implementation file (with extension .cpp, or .cc etc.). The way we have the various compilation units "communicate" with each other is with header files and functions, rather than raw data.
Suppose we have an implementation file main.cc and a second implementation file human.cc. We want main.cc to communicate with human.cc. Here we go:
// main.cc
#include "human.hh"
int main()
{
make_the_human_dance(60);
return 0;
}
// human.hh
void make_the_human_dance(int duration);
// human.cc
#include "human.hh"
void make_the_human_dance(int duration)
{
// define how a human dances properly
// ...
}
Under the same principle you can use classes for communication. Declare the class in the header file and define the class' methods in the implementation file. Sometimes you must provide the implementation of functions in the header files, but that is already going offtopic.
You could declare a global variable in a header file like so:
extern int GlobalVar;
And in exactly one compilation-unit (cpp-file) you have to initialize it:
int GlobalVar = 5;
Any other compilation unit that includes the header now shares the same instance of the global variable (I hope that syntax is correct, i rarely use it).
One should mention, that your question indicates a general lack of understanding of how programs in C++ should be organized. In short, you usually have a file called main.cpp that contains the entry-point of your program. The rest, in C++, is done in classes most of the time. A class is usually split into two parts, the declaration of the class in a header file, and the implementation of the class in a cpp file. To use a class, you include the corresponding header file. This is the short version, and there is much more to tell, but this should give you a good starting point.
Normally you define a function in one cpp file, then declare that function as extern in a header, and include the header in whatever other cpp file needs to use the function. You can then write code that calls the function normally. At link time you need to supply the object files that resulted from both cpp files, and the linker ...links them together, so the function call in one file passes the value correctly as you call the function that was defined in the other cpp file.
Referencing code in a different file typically makes use of #include