This question already has answers here:
Header/Include guards don't work?
(6 answers)
Closed 6 years ago.
im searching the internet for about half an hour because of a (actually basic and simple) problem in C++. Maybe im missing something, but I don't know what. Lets say, i have 3 files: "main.cpp", "dosomething.cpp" and "Header.h".
"Header.h":
#pragma once
#ifndef HEADER_H
#define HEADER_H
char text[] = "This is a text";
#endif // !HEADER_H
"main.cpp"
#include <stdio.h>
#include <iostream>
#include "Header.h"
using namespace std;
void main() {
cout << text << endl;
}
and "dosomething.cpp"
#include "Header.h"
void dosth() {
}
Now the compiler/linker tells me that "text" is already defined in another file. Why? I know how guard idioms such as #pragma once and #ifndef etc. work - atleast I think so. I have no idea whats wrong here. The code itself works (when not including the header in "dosomething.cpp").
Any idea?
Edit: Im using Visual Studio 2015
You need to put extern keyword. C/C++ does for every .c/.cpp file will combine the text of files and all definitions will be merged in the linking step. If you write 'extern' before the header variable, you can define it in just one C++ file, and all other files will reuse it. The linker will use just one instance of the variable you externed it to.
So in header.h
#pragma once
extern char text[];
main.cpp remains the same, but"dosomething.cpp" changes slightly
#include "Header.h"
(...)
char text[] = "...";
(...)
https://en.wikipedia.org/wiki/External_variable
Related
While following the book C++ For Dummies, I have three files in my CodeBlocks project, main.cpp, Pen.h, and Pen.cpp. They look like this:
main.cpp:
#include <iostream>
#include "Pen.h"
//#include "Pen.cpp"
using namespace std;
int main()
{
Pen MyPen = Pen();
MyPen.test();
}
Pen.h:
#ifndef PEN_H_INCLUDED
#define PEN_H_INCLUDED
//#include "Pen.cpp" // Uncommenting this gives a different error
using namespace std;
class Pen
{
public:
// attributes omitted
// PROTOTYPES:
// other functions omitted
void test();
};
#endif // PEN_H_INCLUDED
Pen.cpp:
#include <iostream>
#include "Pen.h"
using namespace std;
//other function definitions omitted
void Pen::test()
{
cout << "Test successful." << endl;
}
When I run the code as listed above, I get an "undefined reference to `Pen::test()'" error. To fix this, I changed the #include statements at the top of main.cpp to:
#include <iostream>
//#include "Pen.h"
#include "Pen.cpp"
This works as intended and correctly prints out "Test successful."
My question is this: what in the world is the point of putting a function prototype in a header file if I have to import the .cpp file later on anyways?
EDIT: It turns out this was a problem with not knowing how to use Code::Blocks rather than with the C++ language.
Assuming you're using gcc, you can compile and link in one step by supplying multiple .cpp files via the command line.
g++ Pen.cpp main.cpp
clang should be similar.
clang++ Pen.cpp main.cpp
An #include should never reference a .cpp file. At all. There's no good reason to do it. Include your headers and then supply the names of all .cpp files when you compile. If your project gets big and you have too many .cpp files to reasonably list, then it's time to break out a makefile or similar.
In the main.cpp include the header file:
#include "Pen.h"
The Pen.h file it's ok.
You need to add the Pen.cpp file to the project tree.
Go to Project -> Add files... and add Pen.cpp
This question already has answers here:
Generate include file name in a macro
(3 answers)
Closed 2 years ago.
I am trying to include a header file whose name is version dependent. The concrete name
is given by concatenation of strings with the version number. The last one is retrieved
from CMakeLists.txt using a configuration file.
#include "config.h" # load PROJECT_VER
#define HEADERROOT "foo-"
#define HEADERBASENAME HEADERROOT PROJECT_VER
#define HEADER HEADERBASENAME ".h"
// Equivalent to: #define HEADER "foo-5.1.h"
The string generated is correct, however, it is not possible to include it (appending to the previous statements)
#include HEADER
#include <iostream>
using namespace std;
int main() {
cout << HEADER << endl;
return 0;
}
The error is
main.cpp:6:10: warning: extra tokens at end of #include directive
#include HEADER
^~~~~~
main.cpp:6:16: fatal error: foo-: No such file or directory
#include HEADER
^
compilation terminated.
You can't use a macro to define the filename for an #include statement. This kind of task is better handled in an external build process that creates the necessary source code before the preprocessor/compiler is then invoked.
Ok so, simply said : I've included a .h into another .h and i get a compilation error telling me that the functions are already defined in main.obj
But, well i've only included Graphics.h one time so how can it be possible that main.obj also defined the Graphics.h functions ?
I got an Error LNK2005 "Already defined in main.obj".
Graphics.h contain functions that many others files will need, but for the moment we have a problem with just one file so I'd like to fix that first.
EDIT : SOLVED by spliting the header, i kept the header for the functions prototypes and I created a new Graphics.cpp for the functions definition
Here are the most concerned files, I've commented the files content so it is readable.
If I'm wrong by commenting please tell me and I'll put it on pastebin or something like that
main.cpp
#include "main.h"
using namespace std;
int main()
{
sMainData data = {};
main_Initialize(data);
while (data.config.window.isOpen())
{
main_Event(data);
main_Update(data);
main_Draw(data);
}
return 0;
}
main.h file :
#ifndef MAIN_H
#define MAIN_H
#include <SFML/Graphics.hpp>
#include "PlayerClass.h"
// Structures...
// Prototypes...
// Functions...
#endif // !MAIN_H
PlayerClass.h file :
#ifndef PLAYERCLASS_H
#define PLAYERCLASS_H
#include "AliveClass.h" // Including the mother
#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>
#include "Graphics.h" // <-- So here we have our man
//Class definition
#endif // !1
Graphics.h file :
#ifndef GRAPHICS_H
#define GRAPHICS_H
#include "SFML/Graphics.hpp"
// Prototypes...
// Functions...
#endif // !GRAPHICS_H
You didn't provide a minimal reproducible example, but my best guess is, you have some function implemented in the header file, while ending up including that header, either directly or indirectly, in more than one cpp file. The result is exactly the same function with exactly the same signature, being compiled in both cpp files, which causes the linker to complain.
Solutions:
Move the function out of the header and into its own cpp file (probably the best)
Find a way to only include the header in one single cpp file (probably the second best in case the header isnt yours and you don't want to touch it)
Make that function inline (probably the easiest, but technically the worst)
I've been teaching myself some OpenGL using SFML for creating windows/handling inputs, etc. My main.cpp started getting a bit unwieldy so I decided to start splitting my code up. I created a 4X_vertex.h and a 4X_vertex.cpp (4X is the name of the project) and moved the relevant functions and structs out of my main and into these files. However, when I compile, I get the error
variable or field "drawVertexArray" declared void
which from my research seems to be just an unhelpful message relating to the next error, which is
vertex was not declared in this scope
Here's my list of includes from my main.cpp:
#include <iostream>
#include <fstream>
#include <string>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include "4x_vertex.h"
#include "4x_constants.h"
My 4X_vertex.h:
#ifndef _4X_VERT_H
#define _4X_VERT_H
struct vertex{
GLfloat x,y,z;
GLfloat r,g,b;
};
void drawVertexArray(vertex v[]);
vertex* loadVertexData();
#include "4X_vertex.cpp"
#endif
The part of 4X_vertex.cpp that's giving me the trouble:
using namespace std;
void drawVertexArray(vertex v[]){
... openGL stuff...
}
All of this worked before I started moving it around so I'm assuming there's something weird going on with the includes, or something. All help is greatly appreciated!
Just some pointers. Best practice is to divide your project up into multiple source files. Typically, you would use the word "main" in the file name of the main source file (if applicable). So you might have something like...
main.cpp
feature1.cpp
feature2.cpp
tools.cpp
For your other files, you will typically name them after the class they implement. You will most often have both a .h and a .cpp. Put your declarations in the .h and your definitions in the .cpp had have the .cpp include the .h. That might give you...
main.cpp
feature1.cpp feature1.h
feature2.cpp feature2.h
tools.cpp tools.h
The modules that reference one of your classes includes it's .h as well. So, main.cpp might look like...
#include <iostream>
#include "feature1.h"
#include "feature2.h"
using namespace std;
void main(int argc, char **argv)
{ ...
cout << "Done!\n";
}
And feature1.cpp might be...
#include "feature1.h"
#include "tools.h"
feature1_class::feature1_class() { ... }
void feature1_class::AUsefulFeature(int val) { ... }
//etc.
...where feature1.h declares the class, defined constants, etc. f.g.,
#ifndef FEATURE1
#define FEATURE1
#include "tools.h"
class feature1_class
{
public:
feature1_class();
void AUsefulFeature(int val);
int APublicMember;
};
#endif
You may have noticed that tools.h is actually include twice in feature1.cpp. It is included from within the feature1.h and explicitly from the .cpp file. If you use the following pattern in your .h files ...
#ifndef TOOLS_H
#define TOOLS_H
//... do your thing
#endif
... then multiple includes shouldn't cause you any problems. And as you refactor code, it is one less thing to have to worry about cleaning up.
If you have been using a single file for all your source up till now, you may have been compiling like so...
cl main.cpp
Which gives you your .exe and .obj and maybe other files. But with multiple source files involved, it isnt much different. You can say...
cl main.cpp feature1.cpp feature2.cpp tools.cpp
There is much more to learn, but this is a start and helps you on the way to better organization of your coding thoughts.
You need to #include "4X_vertex.h" at the top of your 4X_vertex.cpp file. This will allow the .cpp file to see the declaration for the struct vertex.
In general, each file (both .h and .cpp files) needs to #include any header files which contain declarations for items used in that file. This includes the standard headers and OpenGL headers, as well as your custom ones.
I'm making an app with DragonFireSDK and I want to organize my multi thousand line app with .cpp and .h files
I get tons of errors when trying to do stuff though
So my app.cpp (main, required one) looks like this
Code:
#include "DragonFireSDK.h"
#include "SaveData.h"
#include "Structures.h"
#include "Definitions.h"
#include "Variables.h"
#include "SaveData.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "Functions.cpp"
#include "AppMain.cpp"
#include "AppExit.cpp"
#include "OnTimer.cpp"
The #include "SaveData.h" through #include "Variables.h"
all have something like
Code:
#ifndef _HeaderName
#define _HeaderName
//STUFF HERE LIKE
#define player1 0
#define player2 1
//OR
typedef struct _number {
int view;
int number;
bool able;
int opacity;
};_number number[4];
//OR
int whoseturn;
int bet[5];
bool reachedmax[5];
int playerimg[5];
#endif
Now I may be doing something wrong already but here's some more...
My AppMain.cpp, OnTimer.cpp etc look like this
(AppMain(), etc are required functions too)
Code:
#include "DragonFireSDK.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "Definitions.h"
#include "Structures.h"
#include "Variables.h"
#include "SaveData.h"
#include "Functions.cpp"
void AppMain() {
//STUFF HERE
};
Now this is where I think the problem is...
Functions.cpp
Code:
#include "DragonFireSDK.h"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "SaveData.h"
#include "Structures.h"
#include "Definitions.h"
#include "Variables.h"
//SOME FUNCTIONS
void SavePlayerMoney();
void SetInfo (int idnum, bool actuallyset = false);
void SwitchButton (int idnum, bool makeactive=true);
void DisableButton (int idnum);
double round (double number);
void SavePlayerMoney() {
//...
}
void SetInfo(int idnum, bool actuallyset) {
//...
}
void SwitchButton(int idnum, bool makeactive) {
//...
}
void DisableButton(int idnum){
//...
}
Now the errors I get after I thought if fixed all the stuff...
Code:
1>AppMain.obj : error LNK2005: "void __cdecl SwitchButton(int,bool)" (?SwitchButton##YAXH_N#Z) already defined in App.obj
1>AppMain.obj : error LNK2005: "double __cdecl round(double)" (?round##YANN#Z) already defined in App.obj
1>AppMain.obj : error LNK2005: "void __cdecl SetInfo(int,bool)" (?SetInfo##YAXH_N#Z) already defined in App.obj
1>AppMain.obj : error LNK2005: "int __cdecl Digits(int)" (?Digits##YAHH#Z) already defined in App.obj
Any help is very greatly appreciated!
Don't #include the .cpp files.
The C compilation model is that each function is defined precisely once, i.e. in exactly one compilation unit (i.e. one object file). You compile each source file independently into a separate object file (#include-ing header files so that the compiler knows e.g. the prototype of functions to be used). You then link these separate object files together to form the final executable.
If you #include the .cpp files, you will end up with the same function being defined in multiple compilation units (remember that #include is basically equivalent to copy-pasting the contents into the file that's doing the including). So the linker will get confused, and give you the messages that you are seeing.
UPDATE
Oh, I see the problem is that you don't have a corresponding header file for Functions.cpp. The idea is that you also write a Functions.h, along the lines of:
#ifndef FUNCTIONS_H_
#define FUNCTIONS_H_
void SavePlayerMoney();
void SetInfo(int idnum, bool actuallyset);
void SwitchButton(int idnum, bool makeactive);
void DisableButton(int idnum);
#endif
And then you #include this header file, rather than the .cpp file.
The linker complains because functions are defined more than once. A function may only be defined in one translation unit (cpp file, after compilation it becomes an obj file) - except if it is declared inline.
You're including Functions.cpp in other units, so the function definitions from Function.cpp get duplicated into those, thus causing the linker trouble.
The solution would be to declare the functions inline - or, even better, declare them in a header (i.e. Functions.h) and define them in Functions.cpp. Any users of those functions may then #include Functions.h and have access to these functions even though they don't know their implementation.
To declare a function, do: int foo();, to actually define it, do int foo() { your code goes here}.
I think everyone answered this really well so I'm just going to give you my C++ philosophy on big projects because it seems like it is information that you may find useful.
ALWAYS separate function declarations and implementation.
It will make your life considerably easier. Declare function prototypes in a .h file, then write the implementation in a .cpp file.
For example:
// mystuff.h
#ifndef MYSTUFF_H
#define MYSTUFF_H
int myFunction(int value, char letter);
#endif
And in my .cpp file:
// mystuff.cpp
#include "mystuff.h"
int myFunction(int value, char letter) {
// insert implementation here
}
Why do this? Well one great reason is that when your code doesn't work (as it ostensibly will, an inescapable reality for any programmer), you can substitute out your .cpp file with alternate implementations without modifying the structure of your code. Not only that, there are various tricks you will discover that will rely on separating declarations and implementation that will ease your life considerably. Bottom line, do it.
Attempt encapsulation wherever possible.
If you're doing a big project (and you will notice this is true for most big projects you encounter), encapsulating similar functions, variables, and the like will save you considerable time and energy. It seems like you're making a program to play a game- have you thought about encapsulating each player into a Player or Human class, with class-specific functions for each one? If you're a C++ or Java junkie like myself, you will find that an object-oriented approach is the most effective approach 99 times out of 100 (the 1% of situations is usually where you have helper functions that don't really fit in any of the objects you've defined).
Also, encapsulation enables you to take advantage of the two other fundamental principles of object-oriented design- polymorphism and inheritance. For example, you could define a Player class, then if your game involves a computer player and a human player, you could write a separate class for each of them that inherits the basic functionality of a Player but implements each function of a Player in a different way (i.e. if there is a makeMove function, you would have a different implementation for a human than a computer. Thus, inheritance greatly simplifies your job). There are obviously many qualities of OO design that are appealing, but for what I've gleaned from your code, I'd say you would benefit the most from these ones.
Obviously, this is my own philosophy and not one that I wish to forcefully impose on you. But hopefully you will take a few helpful tips out of my terse rambling to improve the way you write code and/or avoid long lists of errors. Best of luck!
Move your function declarations to header files. For example, looks like Functions.h should contain:
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
//SOME FUNCTIONS
void SavePlayerMoney();
void SetInfo (int idnum, bool actuallyset = false);
void SwitchButton (int idnum, bool makeactive=true);
void DisableButton (int idnum);
double round (double number);
#endif
Then Functions.cpp can just include Functions.h instead of those declarations. Some header files may need to include other header files to get the appropriate types.
Finally, never #include a *.cpp file.