Sorry for this question, which is probably a pretty nooby question, but i just don't know how to get my problem solved.
I have a function that returns true or false, rather the one number is a divider of an other number or not.
Now i need this function in two of my programs and instead of just copy-pasting it, i want to write this function in its own file and then include it in the programs.
What is the best way to do that?
I don't use VisualStudio, so I think I can't create a library.
You can create a header-only "library". That is, a single header file, say "my.h", which contains the definition of your function:
#ifndef MY_LIBRARY_UNIQUE_ID_OR_SOMETHING //these are called include guards,
#define MY_LIBRARY_UNIQUE_ID_OR_SOMETHING //look them up
inline bool myFunc()
{
return true;
}
#endif
Do note that the function must be inline. Otherwise you may get "function redefinition" linker errors.
In order to use this "library", all you have to do is #include "my.h" (with correct path, of course). Hope this helps
Create a file with an extension .h. For example: myheader.h
Then write to myheader.h the following:
#ifndef MYHEADER_H
#define MYHEADER_H
bool is_divider(int, int);
#endif
Write a source file named myheader.cpp
Inside the myheader.cpp write:
#include"myheader.h"
bool is_divider(int a, int b) {
/your code here
}
include the header myheader.h to the files you need to use is_divider()
Note that if you are using an IDE you should do the following:
Add the .cpp and .h files to your project
Include the path of the headers on the IDE options.
For example, if you are using codeblocks you can see the process here (keep in mind that same procedure applies in other IDE's as well)
If you are using a terminal and an editor you can create a makefile. A nice tutorial can be found here
Use a header file to share the function between both programs. The header file extension can take different forms. The most common extension is .h however there are others such as .hpp.
For example, a header file named foo.h might contain:
#pragma once // include this file just once
inline bool foo()
{
return false;
}
To use the header file you would include it from the .cpp file as follows:
#include "foo.h" // when foo.h is located in the same directory as the .cpp file
#include <foo.h> // when foo.h is located in a project additional include folder
#include "../foo.h" //when foo.h is located up one directory from the .cpp file
You need to create a header file with the function. Here are 3 options:
Option 1
Define function in header file
Here is an example:
Create a file header.h
Give it the following code:
#pragma once
inline int random()
{
return 4; //Strictly random
}
If your compiler doesn't support #pragma, use header guards, like this:
#ifndef HEADER_H_OR_ID
#define HEADER_ H_OR_ID
inline int random()
{
return 4; //Strictly random
}
#endif
For this option, every file that wants to use the function has to include "header.h"
Option 2
Forward declare the function in a header file, and implement in every source file
Example:
#ifndef HEADER_H_OR_ID
#define HEADER_H_OR_ID
int random();
#endif
Source.cpp
#include "header.h"
int random() {return 4;}
But unfortunately, this is not probably not what you want, although it allows uniqueness per file.
Option 3
Forward declare the function in a header file, and implement in corresponding source file
Example:
Header.h
#ifndef HEADER_H
#define HEADER_H
int random();
#endif
Header.cpp
#include "Header.h"
int random() {return 4;}
Here, you have to include the source file with the main file, such as by linking them on the command line like this:
g++ main.cpp header.cpp
Tools like Visual Studio already would link all files, so nothing manual, other than creating files, is necessary.
Related
I have a header file x.h which is included by more than one *.c source files.
This header file has some structure variables defined.
I have put multiple inclusion prevention guard at the beginning of the header file as:
#ifndef X_H
#define X_H
...
..
//header file declarations and definitons.
#endif//X_H
On building I get linker errors related to multiple definitions. I understand the problem.
Won't a multiple inclusion prevention guard at the top of header file as I have, prevent multiple inclusions of the header file x.h and thereby avoid multiple definitions of the variables that are there in x.h?
#pragma once does not work on this particular compiler, so what is the solution?
Someone had posted this answer to a similar question. It doesn't seem to work for me. How does this solution work?
If the linker is complaining, it means you have definitions rather than just declarations in your header. Here's an example of things that would be wrong.
#ifndef X_H
#define X_H
int myFunc()
{
return 42; // Wrong! definition in header.
}
int myVar; // Wrong! definition in header.
#endif
You should split this into source and header file like this:
Header:
#ifndef X_H
#define X_H
extern int myFunc();
extern int myVar;
#endif
C Source:
int myFunc()
{
return 42;
}
int myVar;
Header guards are only good for a single compilation unit, i.e., source file. If you happen to include a header file multiple times, perhaps because all headers included from main.c in turn include stdio.h then guards will help.
If you have the definition of a function f in x.h which is included by main.c and util.c, then it is like copying and pasting the definition of f into main.c when creating main.o and doing the same for util.c to create util.o. Then the linker will complain and this happens despite your header guards. Having multiple #include "x.h" statements in main.c is possible of course because of these guards.
Using include guards prevents one compilation unit from including the header twice. E.g. if header B.h includes A.h and B.cpp includes A.h and B.h, everything from A.h would be declared twice in the compilation B.cpp if you weren't using include guards.
Your include guards prevent this from happening, all's fine till now.
But you get multiple definitions at link time, i.e. two compilation units define the same thing, this probably means you got a real definition in your header, use extern for all variables, make sure functions are either inline or are defined in the cpp file.
If the functions aren't large, you can use "inline" before them and the linker won't complain.
Using a multiple inclusion guard prevents compiler errors, but you're getting a linker error. Do you have data definitions in the header file that don't use extern?
Maybe X_H is already defined somewhere else? I just ran into this issue, where Xlib defines X_H in /usr/include/X11/X.h.
To check, you can call gcc -dM -E (if you are using gcc), e.g. in the buildsystem I’m using that works with CC=gcc CFLAGS="-dM -E" make. If the output file contains #define X_H even though you remove it from your file (use Y_H for example), then it is already defined outside your source code.
I have a header file x.h which is included by more than one *.c source files.
This header file has some structure variables defined.
I have put multiple inclusion prevention guard at the beginning of the header file as:
#ifndef X_H
#define X_H
...
..
//header file declarations and definitons.
#endif//X_H
On building I get linker errors related to multiple definitions. I understand the problem.
Won't a multiple inclusion prevention guard at the top of header file as I have, prevent multiple inclusions of the header file x.h and thereby avoid multiple definitions of the variables that are there in x.h?
#pragma once does not work on this particular compiler, so what is the solution?
Someone had posted this answer to a similar question. It doesn't seem to work for me. How does this solution work?
If the linker is complaining, it means you have definitions rather than just declarations in your header. Here's an example of things that would be wrong.
#ifndef X_H
#define X_H
int myFunc()
{
return 42; // Wrong! definition in header.
}
int myVar; // Wrong! definition in header.
#endif
You should split this into source and header file like this:
Header:
#ifndef X_H
#define X_H
extern int myFunc();
extern int myVar;
#endif
C Source:
int myFunc()
{
return 42;
}
int myVar;
Header guards are only good for a single compilation unit, i.e., source file. If you happen to include a header file multiple times, perhaps because all headers included from main.c in turn include stdio.h then guards will help.
If you have the definition of a function f in x.h which is included by main.c and util.c, then it is like copying and pasting the definition of f into main.c when creating main.o and doing the same for util.c to create util.o. Then the linker will complain and this happens despite your header guards. Having multiple #include "x.h" statements in main.c is possible of course because of these guards.
Using include guards prevents one compilation unit from including the header twice. E.g. if header B.h includes A.h and B.cpp includes A.h and B.h, everything from A.h would be declared twice in the compilation B.cpp if you weren't using include guards.
Your include guards prevent this from happening, all's fine till now.
But you get multiple definitions at link time, i.e. two compilation units define the same thing, this probably means you got a real definition in your header, use extern for all variables, make sure functions are either inline or are defined in the cpp file.
If the functions aren't large, you can use "inline" before them and the linker won't complain.
Using a multiple inclusion guard prevents compiler errors, but you're getting a linker error. Do you have data definitions in the header file that don't use extern?
Maybe X_H is already defined somewhere else? I just ran into this issue, where Xlib defines X_H in /usr/include/X11/X.h.
To check, you can call gcc -dM -E (if you are using gcc), e.g. in the buildsystem I’m using that works with CC=gcc CFLAGS="-dM -E" make. If the output file contains #define X_H even though you remove it from your file (use Y_H for example), then it is already defined outside your source code.
Suppose I have a header file which should be including another header file but doesn't (for whatever reason). For example:
myHeader.h
#ifndef MYHEADER_H
#define MYHEADER_H
struct i
{
uint32_t field; // Forgot to include <cstdint>
};
#endif
This mistake can be easily hidden in the .c/.cpp files. For instance like this:
someFile.cpp
#include "myOtherHeader.h" // <cstdint> gets included through this file
#include "myHeader.h"
struct i someStruct;
someFile.cpp will compile just fine and hide the fact that I missed including cstdint in myHeader.h. This isn't a problem here, but suppose when I want to use myHeader.h in some other .cpp file, that could cause a problem.
Is there a simple way to detect this omission of the header file? There are unpleasant ways, like manually looking over the file (but that is tedious and error prone), or creating a dummy .cpp file and including just the header file in question (but that isn't scalable to a large number of header files). Is there some static analysis tool or method that would check this for me?
You do it manually.
It's kind of silly to sit through and write code to check for you and paste it in every file when you can spend a 100th of that time just heading to the top and pasting the include statement in.
When coding in either C or C++, where should I have the #include's?
callback.h:
#ifndef _CALLBACK_H_
#define _CALLBACK_H_
#include <sndfile.h>
#include "main.h"
void on_button_apply_clicked(GtkButton* button, struct user_data_s* data);
void on_button_cancel_clicked(GtkButton* button, struct user_data_s* data);
#endif
callback.c:
#include <stdlib.h>
#include <math.h>
#include "config.h"
#include "callback.h"
#include "play.h"
void on_button_apply_clicked(GtkButton* button, struct user_data_s* data) {
gint page;
page = gtk_notebook_get_current_page(GTK_NOTEBOOK(data->notebook));
...
Should all includes be in either the .h or .c / .cpp, or both like I have done here?
Put as much as you can in the .c and as little as possible in the .h. The includes in the .c are only included when that one file is compiled, but the includes for the .h have to be included by every file that uses it.
The only time you should include a header within another .h file is if you need to access a type definition in that header; for example:
#ifndef MY_HEADER_H
#define MY_HEADER_H
#include <stdio.h>
void doStuffWith(FILE *f); // need the definition of FILE from stdio.h
#endif
If header A depends on header B such as the example above, then header A should include header B directly. Do NOT try to order your includes in the .c file to satisfy dependencies (that is, including header B before header A); that is a big ol' pile of heartburn waiting to happen. I mean it. I've been in that movie several times, and it always ended with Tokyo in flames.
Yes, this can result in files being included multiple times, but if they have proper include guards set up to protect against multiple declaration/definition errors, then a few extra seconds of build time isn't worth worrying about. Trying to manage dependencies manually is a pain in the ass.
Of course, you shouldn't be including files where you don't need to.
Put as many includes in your cpp as possible and only the ones that are needed by the hpp file in the hpp. I believe this will help to speed up compilation, as hpp files will be cross-referenced less.
Also consider using forward declarations in your hpp file to further reduce the include dependency chain.
If I #include <callback.h>, I don't want to have to #include lots of other header files to get my code to compile. In callback.h you should include everything needed to compile against it. But nothing more.
Consider whether using forward declarations in your header file (such as class GtkButton;) will suffice, allowing you to reduce the number of #include directives in the header (and, in turn, my compilation time and complexity).
I propose to simply include an All.h in the project that includes all the headers needed, and every other .h file calls All.h and every .c/.cpp file only includes its own header.
I have successfully added a dynamic library to a program, but when I try to include the header file in a second file of the project I get errors about class redeclaration. I will add more info if this isn't enough
You need to put guards into your header so it isn't included multiple times. For file 'my.h', you can add something along the lines of:
#ifndef MY_H
#define MY_H
// Header declarations here
#endif
This way, you can include the .h file multiple times but it will only be included the first time.
An #include will replace the #include statement with the files content; having multiple #include's of the same file will therefore redefine the elements multiple times. The typical way is a safeguard like:
/* file foo .h */
#ifndef _FOO_H
#define _FOO_H
/* content */
#endif