This question already has answers here:
C++ Header Files, Code Separation
(4 answers)
Closed 8 years ago.
I've been writing in C++ lately and I'm getting confused with .cpp vs .h — when to use them and what should go in them. I've been reading that you should put function definitions in a separate .cpp file, and headers should be used for declarations, but how do I use the separate .cpp file? Do I #include it or what? I'm looking for clarification on .h and .cpp and what should go where and how to include separate .cpp files.
You should use .h file for function prototype and data type declarations and also for pre-processor directives, and .cpp files for definitions. For example, test.h might be look like
#define CONSTANT 123 // pre-processor directive
void myfunction(char* str);
and your test.cpp might look like
#include <stdio.h>
#include "test.h"
int main(int argc char **argv)
{
myfunction("Hello World");
return 0;
}
void myfunction (char* str)
{
printf("%s and constant %d", str, CONSTANT);
return;
}
Usually the class declaration goes into the (.h) header file, and the implementation goes in the .cpp file.
You include the header file in the cpp file, so all the functions will be recognized, and you should remember to use #ifndef in the header file to avoid errors (includes loops)
Related
This question already has answers here:
When should I write the keyword 'inline' for a function/method?
(16 answers)
Closed 2 years ago.
nice to meet you, Stack overflow residents! Have a question:
I'm using Visual Studio 2019 that says me that I've defined some methods multiple times.
I have a header file (for example):
// header.hpp
#ifndef HEADER_HPP
#define HEADER_HPP
#include <iostream>
struct a {
a();
};
#include "degradation.inl"
#endif HEADER_HPP
And the .inl file for definitions (for example):
// degradation.inl
a::a() {
cout << "the hopless one\n";
}
So, the problem is, when I include this with #include <header.hpp> (that is, I've configured the include paths), have something that looks like that (for example):
error LNK2005: "public: __cdecl a::a(void)" (s0mEsтR#njeSуМb0ls) already defined in helpme.obj
Well, it's not the actual code (you can find the actual code here: GitHub), but I think that this code is a good example.
A #include is logically equivalent to inserting the entire contents of the included file into the file that includes it. It's exactly as if the contents of the included file were present in the file that included it. And this applies recursively.
If you work out, on paper and pencil, what happens here, this means that every .cpp that #includes what's shown will define a::a(), and compile it as part of the .cpp.
That is the reason for your duplicate symbol when linking. The simplest solution is to simply move the definition of a::a() into its own, separate, .cpp file. Don't #include it from any header, just compile and link it together with the rest of your .cpp files.
Just change
a::a() {
cout << "the hopless one\n";
}
to
inline a::a() {
cout << "the hopless one\n";
}
If you define functions in header files they should be inline (templates are an exception).
This question already has answers here:
Separating class code into a header and cpp file
(8 answers)
Closed 3 years ago.
header file contains declaration of a method and library contains the implementation of that method .I saw a video on Youtube on how to create our own header files, but in that video he was also giving the implementation. My question is that we are creating our own header files then we should also create a library corresponding to our own header files. how to do so?
It is indeed recommended to separate the implementation from the declaration. You don't need to create a library to do that. You can simply write the declaration in a header file and the implementation in a source file.
For example
header.h:
#pragma once
void add(int first, int second);//this is a declaration for "add"
source.cpp:
#include "header.h"
void add(int first, int second) {
return first + second;//this is an implementation for "add"
}
You don't have to call your header file "header.h" and you don't have to call your source file "source.cpp"
How to make a library
There are two types of libraries.
Static library
static libraries are libraries linked at buildtime.
The steps to make one depend on your IDE. Assuming you use Visual Studio IDE check out this walkthrough.
Dynamic library
dynamic libraries are libraries linked at runtime.
The steps to make and use one depends on your IDE and platform. Assuming you use Visual Studio IDE on Windows check out this walkthrough
In c++, you will usually find header (.h) and source (.cpp) file pairs. You are correct that the source files are used for the implementation. See Using G++ to compile multiple .cpp and .h files if you want to compile.
A small example:
MyClass.h:
#ifndef MYCLASS_H // These are called header guards
#define MYCLASS_H
class MyClass {
// constructor
MyClass();
// member that prints "Hello, world."
void hello();
}
#endif // MYCLASS_H
MyClass.cpp:
#include "MyClass.h"
#include <iostream>
// Implementation of constructor
MyClass::MyClass()
{
std::cout << "Constructed MyClass object." << std::endl;
}
// Implementation of hello
void MyClass::hello()
{
std::cout << "Hello, World." << std::endl;
}
main.cpp
#include "MyClass.h"
int main(int argc, char** argv)
{
MyClass mc;
mc.hello();
return 0;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why does this not prevent multiple function declarations?
Global.h
#ifndef Global_h
#define Global_h
#include <iostream>
unsigned char exitStatus;
#endif
OutputHandler.h
#ifndef OutputHandler_h
#define OutputHandler_h
#include "Global.h"
class OutputHandler {
private:
static bool instanceExists;
// more code
#endif
Root.h
#ifndef Root_h
#define Root_h
// declarations
OutputHandler *output;
#endif
Root.cpp
#include "Root.h"
// gets instance of OutputHandler
// more code
I am getting errors regarding exitStatus, static bool instanceExists, and static class output being already defined by Root.obj in OutputHandler.obj. I assume the issue is with including the header file OutputHandler.h in both Root.h and OutputHandler.cpp. Anyone know how to fix this or how to better organize header files?
Because include guards only work at the translation unit level (you can, for this simple case, consider a single C file to be a translation unit).
That means a single C file, if it includes the header file twice, will not process it the second time due to the include guards.
However, if you include the header from two different C files, each of them will get a copy of the variables defined in that header.
Then, when you link them together, you get the duplicates.
The easiest way to get around this problem is to never define things in headers, only declare them.
So, in the header (eg, xyzzy.h), you have:
extern int xyzzy; // declare but don't define.
and in all the C files that want to use that, put:
$include "xyzzy.h"
and, in one of those C files, also put:
int xyzzy; // define it here, once.
You can think of declaration as a simple "I declare that this exists somewhere, just not here", while definition is "I an creating this here and now".
Declare extern usigned char exitStatus in Global.h and define it in one implementation file.
The problem is during the linking phase; include guards in the headers won't help you.
In C, there is the separate concepts of declarations and definitions. Declarations are what are put into headers; they merely state that a particular variable exists. The definition of a variable is where storage is actually allocated for it.
For example, in your Global.h, you have:
#ifndef Global_h
#define Global_h
#include <iostream>
usigned char exitStatus;
#endif
This is defining a variable called exitStatus, and the linker is complaining because any given variable should only be defined in one place in a program. What you need to do is declare it in the header, and then define it in only one place in a source (*.cpp) file. For example, your header should declare exitStatus with:
extern char exitStatus;
and in only one source file, define it with:
char exitStatus;
The situation is similar for output in Root.h, as well as any other place you should be declaring variables in the header file.
See also: http://www.cprogramming.com/declare_vs_define.html
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;
}
hey everyone, i got code like this:
//a.h
#ifndef SB
#define SB
namespace A{ int a = 10; int b = 10;}
#endif
however, if I imported the a.h in a.cpp file, the compiler would complain:
error LNK2005: "int A::a" (?a#A##3HA) already defined in a.obj
It looks like compiler would combine .h file and .cpp file together without explicit "import" statement. But it doesn't make sense to me that it would happen with the macro guard defined.
I use Visual C++
#include guards prevent one file from including the same .h file multiple times. They don't prevent multiple files from each including the same .h file once, which is what I assume is happening to you. Move your definitions into a single .cpp file and leave just a declaration here:
namespace A {
extern int a;
extern int b;
}
which tells the compiler that these variables exist somewhere, but their definitions can be found elsewhere.
Chances are you have a cyclic #include statement some where that is putting the header file into both object files and then trying to link the object files together gets the duplicate entries.
Remember that when you #include what the compiler is doing is cut/pasting the contents of the .h file in place of the line the include is on.
You will want to declare prototypes in the .h file, not the actual declaration of those objects and their values.
If you want a and b to have constant values, you can do this:
//a.h
#ifndef SB
#define SB
namespace A{const int a = 10; const int b = 10;}
#endif
and it will not be a problem to include it in several places.
If you need the values to change, you should follow dfan's advice.