Header files slow down the program - c++

My program have encountered a strange error: the header files slows the program down. I test the header file with empty code ( that is : main() {} ) and it takes 40s to run that empty code.
Header files .h
#include "stdafx.h"
#include <string>
#ifndef LZ_H
#define LZ_H
extern int e,i;
extern std::string dic[1000000];
void init();
#endif
Functions file .cpp
#include "lz.h"
#include "stdafx.h"
#include <string>
std::string dic[1000000];
int i=0;
int e=0;
std::string cstr(char c)
{
return std::string(1,c);
}
void init()
{
for (e=0;e<=255;e++) dic[e]=cstr(e);
e=e-1;
}
Test main file .cpp
#include "lz.h"
void main() {}
Result: 40s.
I have never faced such strange error before.

By putting a global declarations of one million strings in the .cpp file, you are forcing the compiler to put in the code to create one million string objects when the program starts. This is the reason for your slowdown.
As you are only using the first 256 elements of the array, change it to be of size 256.

Related

Eclipse C++ multiple main error only when using multiple headers

I'm trying to learn how to utilize header files in C++ projects, so I made .cpp files containing simple functions to make sure I'm doing all the declaring and including correctly.
Everything worked fine when I only had one set of .cpp and .h files, but when I try to add more I get errors.
To start with, in my project I had:
helloworld.cpp
#include "helloworld.h"
#include <iostream>
#include <cstdio>
using namespace std;
int HelloWorld() {
puts("Hello, World!");
cout << "Hello, World!" << endl;
return 0;
}
helloworld.h
#ifndef HELLOWORLD_H_INCLUDED
#define HELLOWORLD_H_INCLUDED
int HelloWorld();
#endif /* HELLOWORLD_H_INCLUDED */
main.cpp
#include "helloworld.h"
#include <iostream>
using namespace std;
int main(){
HelloWorld();
return 0;
}
Which built with no errors and ran correctly.
Next I tried adding a second .cpp and .h file, which created building errors.
pointers.cpp
#include "pointers.h"
#include <iostream>
using namespace std;
int Pointers() {
int x = 1;
int *ptr_a = &x;
cout << *ptr_a << endl;
return 0;
}
pointers.h
#ifndef POINTERS_H_INCLUDED
#ifndef POINTERS_H_INCLUDED
int Pointers();
#endif /* POINTERS_H_INCLUDED */
and modified main.cpp:
#include "helloworld.h"
#include "pointers.h"
#include <iostream>
using namespace std;
int main(){
HelloWorld();
Pointers();
return 0;
}
Now when I try to build, I get an error saying there are multiple definitions of main -- one in main.cpp, and the other in pointers.cpp.
Even more oddly, if I make a new project and do the exact same thing but reverse the order in which I create the .cpp and .h files (i.e. pointers first then helloworld), it builds and runs correctly with just the pointers files but runs into the same error when adding helloworld files, saying that the multiple exceptions of main are in main.cpp and helloworld.cpp.
I figure it must have something to do with Eclipse itself, but I don't know what the exact issue is.
Does anyone know what might be going on?

Error messages (multiple defined symbols) after including a class file

I am using the g++ compiler on a linux mint.
I´m tying to make a class for neural Network witch i want play tic tac toe.
My Header:
#ifndef tttAi
#define tttAi
#include <string>
class Synaps{
public:
explicit Synaps(const std::string& n, double v);
void add(double ad);
void multi(double mu);
void save();
double read();
private:
std::string name;
double Syn_value;
};
#endif
My functions are:
#include "tttAi.h"
#include <fstream>
#include <string>
Synaps::Synaps(const std::string& n, double v)
:name(n), Syn_value(v){
}
void Synaps::add(double ad) { //change by addition
Syn_value += ad;
}
void Synaps::multi(double multip) { //change by multiplication
Syn_value *= multip;
}
double Synaps::read() {
return Syn_value;
}
And here is what i wanted it to do:
#include <iostream>
#include "tttAi.h"
#include "tttAi.cpp"
int main() {
Synaps n1n6("n1n6", 75);
n1n6.multi(2);
std::cout << n1n6.read() << '\n';
/*Want it to just output the value of Syn_value Witch at
this point should be 150 if i have done everything right*/
}
Command used: g++ -Wall -std=c++14 *cpp
so what i would think i´d get was just the consol output of 150 but whilst compiling i get this endless error message:
enter image description here
hope you have a idea of what i did wrong, any ideas welcome.
You're including a cpp file containing definitions multiple times (i.e. you should not write
#include "tttAi.cpp"
in your main.cpp file) and therefore violating the ODR - one definition rule.
Remember that including a file means duplicating that file's contents in the point of inclusion (and therefore duplicating your definitions as well).
The problem seems to be #include "tttAi.cpp" in your main.cpp file.
You should not include cpp files
You should not #include .cpp files. Instead, just list them on the command line when you compile.

Why are my functions undefined when I declared the type already?

Hi I was just trying to learn separate Classes in C++. I don't know why my code is not working.
So here is the main file code
#include <iostream>
#include "Number.h"
using namespace std;
int main()
{
Number key;
key.setNumber(200);
cout<<key.getNumber();
return 0;
}
Here is the Class cpp functions file code
#include "Number.h"
#include <iostream>
using namespace std;
void Number::setNumber(int transfernumber)
{
privatenumber = transfernumber;
}
int Number::getNumber()
{
return privatenumber;
}
And here is the header file
#ifndef NUMBER_H
#define NUMBER_H
class Number
{
public:
Number();
void setNumber(int transfernumber);
int getNumber();
private:
int privatenumber;
};
#endif // NUMBER_H
Thanks
In your cpp file you need to define the default constructor for the Number class. For example:
Number::Number() : privatenumber(0) {}
I have test your example. The error happened for the main.cpp cannot found the number.cpp. You have three ways to solve it:
write your main() to the number.cpp, not a solo file.
complie the main.cpp with the linux command gcc or write a Makefile, instead of using codeblocks.
If you want to use the codeblocks for compiling, you should create a project, and then add your three files to the project. Now compile the main.cpp.
Use the three ways above, I think you will compile successfully.
BTW, you should add the Number::Number() 's implementation.

field declared void / struct or variable not declared in this scope

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.

Using multiple headers and cpp files help

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.