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.
Related
I'm too much confused why it's an error to write the same function in two different cpp files?
what if both want to use that function? and why this should ever cause an error, the function is written in to separate files...
a.cpp:
#include "test.h"
b.cpp:
#include "test.h"
test.h
int getMin(int x,int y)
{
return x;
}
plus, why changing test.h to the following won't fix the problem:
#ifndef UNTITLED1_A_H
#define UNTITLED1_A_H
int getMin(int x,int y)
{
return x;
}
#endif
If you define a function twice, the linker will see 2 definitions of the same function, which is not allowed. (even though each .cpp that includes this header file sees only one definition, which is why adding header guards doesn't help here).
One option is to only write the declaration of the function in the .h file, and write the definition in a separate .cpp file. (this is the more common implementation).
If you want to define the function inside the header file, then it needs to be inline, like this:
inline int getMin(int x,int y)
{
return x;
}
Note that if you do the second option, then all files that include this header will need to be recompiled, if you change the internals of this function (this is probably not a good idea, when the interface doesn't change).
You need to make this function "inline" and it will work.
Is there a way to reduce the scope of #include directive?
I mean for example to do something like this
void functionOneDirective()
{
#include "firstInstructionSet.h"
registerObject();
// cannot access instantiate()
}
void functionSecondDirective()
{
#include "secondInstructionSet.h"
instantiate();
// cannot access registerObject()
}
void main()
{
//cannot access instantiate() && registerObject()
}
It is not possible to restrict "includes" to a subset of the using file. It is always visible for anything following the include.
If you are interested in providing "different" views on certain functionality, consider using different namespaces to express these different "views".
#include directly inserts the file contents at the spot. So it depends on the contents of the header, but generally the answer is no. If it's a C header surrounding the inclusion with a namespace might work, but I'm not sure.
#include is resolved during compilation, you can't change it in the code. But you can use preprocessor directives to control which files are included :
#if defined(A) && A > 3
#include 'somefile.h'
#else
#include 'someotherfile.h'
#endif
A possible solution to your question (and the correct way to organize your source code) is to create a separate .c file for each function or group of related functions. For each .c file you also write a .h file that contains the declarations of the elements (types, constants, variables, functions) from the .c file that are published by that file.
The variables declared in the .h file need to be prefixed with the extern keyword (to let the compiler know they reside in a different .c file).
Then, let each .c file include only the .h files it needs (those that declare the functions/types/variables that are used in this .c file).
Example
File firstInstructionSet.h
typedef int number;
void registerObject();
File firstInstructionSet.c
void registerObject()
{
/* code to register the object here */
}
File oneDirective.h
void functionOneDirective();
File oneDirective.c
#include "firstInstructionSet.h"
void functionOneDirective()
{
registerObject();
// cannot access instantiate() because
// the symbol 'instantiate' is not known in this file
}
File secondDirective.h
extern int secondVar;
void functionSecondDirective();
File secondDirective.c
#include "secondInstructionSet.h"
int secondVar = 0;
void functionSecondDirective()
{
instantiate();
// cannot access registerObject() because
// the symbol 'registerObject' is not known in this file
}
File secondInstructionSet.h
void instantiate();
File secondInstructionSet.c
void instantiate()
{
/* code to instantiate here */
}
File main.c
#include "oneDirective.h"
#include "secondDirective.h"
void main()
{
// cannot access instantiate() && registerObject()
// because these symbols are not known in this file.
// but can access functionOneDirective() and functionSecondDirective()
// because the files that declare them are included (i.e. these
// symbols are known at this point
// it also can access variable "secondVar" and type "number"
}
I have read in places like here that you have to include .h files and not .cpp files, because otherwise then you get an error. So for example
main.cpp
#include <iostream>
#include "foop.h"
int main(int argc, char *argv[])
{
int x=42;
std::cout << x <<std::endl;
std::cout << foo(x) << std::endl;
return 0;
}
foop.h
#ifndef FOOP_H
#define FOOP_H
int foo(int a);
#endif
foop.cpp
int foo(int a){
return ++a;
}
works, but if I replace #include "foop.h" with #include "foop.cpp" I get an error (Using Dev C++ 4.9.9.2, Windows):
multiple definition of foo(int)
first defined here
Why is this?
What include does is copying all the contents from the file (which is the argument inside the <> or the "" ), so when the preproccesor finishes its work main.cpp will look like:
// iostream stuff
int foo(int a){
return ++a;
}
int main(int argc, char *argv[])
{
int x=42;
std::cout << x <<std::endl;
std::cout << foo(x) << std::endl;
return 0;
}
So foo will be defined in main.cpp, but a definition also exists in foop.cpp, so the compiler "gets confused" because of the function duplication.
There are many reasons to discourage including a .cpp file, but it isn't strictly disallowed. Your example should compile fine.
The problem is probably that you're compiling both main.cpp and foop.cpp, which means two copies of foop.cpp are being linked together. The linker is complaining about the duplication.
When you say #include "foop.cpp", it is as if you had copied the entire contents of foop.cpp and pasted it into main.cpp.
So when you compile main.cpp, the compiler emits a main.obj that contains the executable code for two functions: main and foo.
When you compile foop.cpp itself, the compiler emits a foop.obj that contains the executable code for function foo.
When you link them together, the compiler sees two definitions for function foo (one from main.obj and the other from foop.obj) and complains that you have multiple definitions.
This boils down to a difference between definitions and declarations.
You can declare functions and variables multiple times, in different translation units, or in the same translation unit. Once you declare a function or a variable, you can use it from that point on.
You can define a non-static function or a variable only once in all of your translation units. Defining non-static items more than once causes linker errors.
Headers generally contain declarations; cpp files contain definitions. When you include a file with definitions more than once, you get duplicates during linking.
In your situation one defintion comes from foo.cpp, and the other definition comes from main.cpp, which includes foo.cpp.
Note: if you change foo to be static, you would have no linking errors. Despite the lack of errors, this is not a good thing to do.
You should just include header file(s).
If you include header file, header file automatically finds .cpp file.
--> This process is done by LINKER.
Because of the One Definition Rule (probably1).
In C++, each non-inline object and function must have exactly one definition within the program. By #includeing the file in which foo(int) is defined (the CPP file), it is defined both in every file where foop.cpp is #included, and in foop.cpp itself (assuming foop.cpp is compiled).
You can make a function inline to override this behavior, but I'm not recommending that here. I have never seen a situation where it is necessary or even desirable to #include a CPP file.
There are situations where it is desireable to include a definition of something. This is specially true when you try to seperate the definition of a template from the declaration of it. In those cases, I name the file HPP rather than CPP to denote the difference.
1: "(probably)" I say probably here because the actual code you've posted should compile without errors, but given the compiler error it seems likely that the code you posted isn't exactly the same as the code you're compiling.
Because your program now contains two copies of the foo function, once inside foo.cpp and once inside main.cpp
Think of #include as an instruction to the compiler to copy/paste the contents of that file into your code, so you'll end up with a processed main.cpp that looks like this
#include <iostream> // actually you'll get the contents of the iostream header here, but I'm not going to include it!
int foo(int a){
return ++a;
}
int main(int argc, char *argv[])
{
int x=42;
std::cout << x <<std::endl;
std::cout << foo(x) << std::endl;
return 0;
}
and foo.cpp
int foo(int a){
return ++a;
}
hence the multiple definition error
So I found that if you are compiling from Visual Studios you just have to exclude the included .cpp file from the final build (that which you are extending from):
Visual Studios: .cpp file > right click > properties > configuration properties >
general > excluded from build > yes
I believe you can also exclude the file when compiling from the command line.
I want to clarify something: including header files is not neccessary to make the linker understand what you want. You can just declare it and it will be linked fine.
main.cpp:
#include <iostream.h>
//not including "foop.cpp"!
int foo(int a);
int main(){
std::cout << foo(4) << std::endln;
}
foop.cpp:
int foo(int a){
return a++;
}
I don't encourage doing like this, but know that headers are not some magic which you have to follow to make the code compile.
Using ".h" method is better
But if you really want to include the .cpp file then make foo(int) static in foo.cpp
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;
}