Static Functions in C++ - c++

I've read a few posts on here about static functions, but still am running into trouble with implementation.
I'm writing a hardcoded example of Dijkstra's algorithm for finding the shortest path.
Declared in Alg.h:
static void dijkstra();
Defined in Alg.cpp:
static void Alg::dijkstra() {
//Create Map
Initialize();
//Loop to pass through grid multiple times
for(int i=0; i<5; i++)
{
current=1;
while(current!=6)
{
//Iterate through and update distances/predecessors
//For loop to go through columns, while current iterates rows
for(int j=1; j<7; j++)
{
//Check if distance from current to this node is less than
//distance already stored in d[j] + weight of edge
if(distanceArray[current][j]+d[current]<d[j])
{
//Update distance
d[j] = distanceArray[current][j]+d[current];
//Update predecessor
p[j] = current;
}
}
//Go to next row in distanceArray[][]
current++;
} //End while
} //End for
output();
} //End Dijkstras
I want to call my function from main without an object. When I had all of this code in Main.cpp, it worked perfectly. Splitting it up into separate files caused the error Main.cpp:15: error: ‘dijkstra’ was not declared in this scope.The posts I came across when searching SE gave me me the impression that to do this, I needed to make that method static, yet I still have no luck.
What am I doing wrong?
Main.cpp:
#include <iostream>
#include "Alg.h"
int main() {
dijkstra();
return 0;
}
Edit: Added full header file, Alg.h:
#ifndef Alg_
#define Alg_
#include <iostream>
#include <stack>
using namespace std;
class Alg
{
public:
void tracePath(int x);
void output();
void printArray();
void Initialize();
static void dijkstra();
int current, mindex;
int distanceArray[7][7]; //2D array to hold the distances from each point to all others
int d[6]; //Single distance array from source to points
int p[6]; //Array to keep predecessors
int copyD[6]; //Copy of d[] used for sorting purposes in tracePath()
int order[6]; //Contains the order of the nodes path lengths in ascending order
}; //End alg class
#endif
Original all-in-one working Main.cpp file: http://pastebin.com/67u9hGsL

You should call it this way:
Alg::dijkstra();
Limitations
Can't call any other class functions that are not static.
Can't access non static class data members.
Can instantiate an object via new class() when constructor is private/protected. E.g. a factory function.

You can just use a namespace instead of having a class with all static members.
Alg.h:
namespace Alg
{
void dijkstra();
}
and in Alg.cpp
namespace Alg
{
void dijkstra()
{
// ... your code
}
}
in main.cpp
#include "Alg.h"
int argc, char **argv)
{
Alg::dijkstra();
return 1;
}

Are you sure the function is supposed to be static?
It looks as if you want just a function?
in your header file:
#ifndef DIJKSTRA_H
#define DIJKSTRA_H
void dijkstra();
#endif
in your cpp file
void dijkstra() {
/* do something */
}
in your main file:
#include "yourcppfile.h"
int main(int argc, char **argv) {
dijkstra();
}
if you really want a static function you have to put it into a nested class:
class Alg {
public:
static void dijkstra();
/* some other class related stuff */
}
the implementation somewhere in a cpp file
void Alg::dijkstra() {
/* your code here */
}
and then in your cpp file where the main resides
#include "your header file.h"
int main(int argc, char **argv) {
Alg::dijkstra();
}

If I remember right any 'static' function is limited to the module in which it is implemented. So, 'static' prevents using the function in another module.

In your header file Alg.h:
#ifndef __ALG_H__
#define __ALG_H__
namespace Alg {
void dijkstra();
}
#endif
The include guards are necessary if you plan to include the header in more than one of your cpp files. It seems you would like to put the function in a namespace Alg, right?
In Alg.cpp:
#include "Alg.h"
void Alg::dijkstra() { /* your implementation here */ }
Then, in main.cpp you call it with full namespace qualification:
#include "Alg.h"
int main() {
Alg::dijkstra();
}
If you just want to distribute your code over several files, I don't see why the function should be declared static.

You are confusing the 'static' keyword for local functions, with the 'static' keyword used in a class to make a function a class function and not an object function.
Remove static the first line of Alg.cpp and in the header file. This will allow Alg.o to contain global symbols that main can refer to and the linker can link.
You still need to call Alg::dijkstra() as was stated by #egur.
After this you may still get errors. The way you are using Alg:: is more like a namespace than a 'class' definition.

Now that we have the complete declaration of your class Arg, it feels like the singleton design pattern could be useful:
http://en.wikipedia.org/wiki/Singleton_pattern

The key here is the ‘dijkstra’ was not declared in this scope error.
Take your all-in-one source file and remove the main function. Make a new source file with this in it:
void dijkstra();
void output();
int main(int argc, char *argv[]) {
dijkstra();
output();
return 0;
}
The all-in-one cpp without a main plus this file above should compile together and give you the same result as before with one source, as it does for me. You will get a duplicate symbol _main error if you forgot to remove the main from the algorithm file.
No static needed.
My answer here fails to touch on good practices on header files, that is, you would want to include those function declarations in a .h file. It solves the compile-time error though.
You may want to find a good book to help you through some of the machinery of C++, where program context (in a linguistic sense) can change the meaning of keywords. This can be bewildering, and it proves to be exactly that for a language with as much colorful history as C++. Take a look here for book suggestions.

Related

How to make it work, problem with 2 classes

i have problem with my small project. I have two classes in it.
Problem:
error: 'Display' was not declared in this scope
Display is a class. Here is code:
//main.cpp
#include <iostream>
#include "Display.h"
#include "Polynomial.h"
using namespace std;
int main()
{
Polynomial prr;
prr.show();
cout<<endl;
cout<<"Enter x= ";
int x;
cin>>x;
cout<<endl;
cout<<"value for x="<<x<<endl<<"y="<<prr.value(x);
Display aa; // this doesn't work
//abc.show();
return 0;
}
//Display.h
#ifndef DISPLAY_H
#define DISPLAY_H
class Display
{
std::vector <vector <char> > graph;
public:
Display(int a, int b);
//friend void lay(Polynomial abc,Display cba);
//void show();
};
#endif // DISPLAY_H
I was thinking that maybe vectors are doing problems. I tested it without vectors, but it didn't change anthing.
//Display.cpp
#include "Display.h"
#include <iostream>
using namespace std;
Display::Display(int a, int b)
{
//ctor
if(a%2==0)
a++;
if(b%2==0)
b++;
vector <char> help;
vector <char> mid;
for(int i=0; i<b; i++)
{
mid.push_back('-');
if(i==(b+1)/2)
help.push_back('|');
else
help.push_back(' ');
}
for(int i=0; i<a; i++)
{
if(i==(a+1)/2)
graph.push_back(mid);
else
graph.push_back(help);
}
}
Now it's Polynomial class it's working fine, but Display class no, and i don't know why.
//Polynomial.h
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
#include <vector>
//class Display;
class Polynomial
{...}
#endif // POLYNOMIAL_H
//Polynomial.cpp
#include "Polynomial.h"
#include <iostream>
#include <windows.h>
#include <cmath>
using namespace std;
// constructors and methods here
// everything here working fine
Edit:
After few tries i am one step back,
Now in Display.h
i have error :
error: 'vector' does not name a type
So i included vector lib.
But it didn't help.
Error Number 1:
You defined a constructor with 2 parameters
Display(int a, int b);
But when you call
Display aa;
Compiler try to instantiate a Display object with a default constructor, that you disabled defining a custom costructor;
you have 2 possibilities:
Adding a default constructor like
Display() = default;
or
Display() { /* do whatever you want to init with default parameter */}
Instantiate your variable using the constructor you defined
Display aa{0,0};
Error number 2:
std::vector < std::vector <char> > graph;
You declared vector<char> instead of std::vector<char>
See a Live Example
One reason is that your Display class has no default constructor, considering you're creating object like Display aa; . A default constructor is the constructor that has no arguments. Default constructors are provided implicitly by compiler as synthesized default constructor only if you don't provide any constructors to your class. If you provide your own constructors to your class, you must also explicitly provide a default constructor. So in your case, you should actually create Display object like this Display aa(argument, argument); by providing arguments. However, If you want to create object like Display aa; then add either Display () { } or Display() = default; in your Display.h file.
Considering you created object like the way I described but still getting an error, another reason could be that you're not compiling the source file that contains the Display (int,int); constructor definition (not just declaration as you did in your header file) along with the source file that contains the main function. If you did that but still getting an error in compilation, then I would assume it is a compiler issue and try adding a forward declaration class Display; which should compile the code. But the definition of Display has to be within the visible range of main function otherwise a forward declaration would do nothing.
In any case, you have to make sure the definition of your class is within the visible range of the main function that creates the class object. A class type with only declaration without a definition is called incomplete type and you cannot create an object of incomplete type. So the declaration of your Display (int,int); constructor in the Display.h is not enough. You also need a definition of that within the visible range of main function. You can either do that in the same file as main, same file as header, or a separate source file (which is the best practice) that has the complete definition of Display class, its data members, and member functions. However, you must make sure to compile that source file along with the source file containing main.

How to make a variable available to multiple .cpp files using a class?

This question has derived from this one.
I have a working program which must be split into multiple parts. In this program is needed to use a variable (now it's a GTK+ one :P) many times in parts of the program that will end up in separated .cpp files.
So, I made a simple example to understand how to make variables available to the program parts. A modified version of the previous code would be:
#include <iostream>
using namespace std;
int entero = 10;
void function()
{
cout<<entero<<endl;
//action1...;
}
void separated_function()
{
cout<<entero<<endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
It is needed to split the code correctly, to have function(), another_function() and main() in separated .cpp files,and make entero avaliable to all of them... BUT:
In the previous question #NeilKirk commented:Do not use global variables. Put the required state into a struct or class, and pass it to functions as necessary as a parameter (And I also have found many web pages pointing that is not recommended to use global variables).
And, as far I can understand, in the answer provided by #PaulH., he is describing how to make variables avaliable by making them global.
This answer was very useful, it worked fine not only with char arrays, but also with ints, strings and GTK+ variables (or pointers to variables :P).
But since this method is not recommended, I would thank anyone who could show what would be the correct way to split the code passing the variables as a function parameter or some other method more recommended than the - working - global variables one.
I researched about parameters and classes, but I'm a newbie, and I messed the code up with no good result.
You need to give the parameter as a reference if you want the same comportement as a global variable
#include <iostream>
using namespace std;
// renamed the parameter to avoid confusion ('entero' is valid though)
void function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value
//action1...;
}
void separated_function(int &ent)
{
cout<<ent<<endl;
++ent; // modify its value again
//action2...;
}
int main( int argc, char *argv[] )
{
int entero = 10; // initializing the variable
// give the parameter by reference => the functions will be able to modify its value
function(entero);
separated_function(entero);
cout<<entero<<endl;
//something else with the mentioned variables...;
return 0;
}
output:
10
11
12
Defining a class or struct in a header file is the way to go, then include the header file in all source files that needs the classes or structures. You can also place function prototypes or preprocessor macros in header files if they are needed by multiple source files, as well as variable declarations (e.g. extern int some_int_var;) and namespace declarations.
You will not get multiple definition errors from defining the classes, because classes is a concept for the compiler to handle, classes themselves are never passed on for the linker where multiple definition errors occurs.
Lets take a simple example, with one header file and two source files.
First the header file, e.g. myheader.h:
#ifndef MYHEADER_H
#define MYHEADER_H
// The above is called include guards (https://en.wikipedia.org/wiki/Include_guard)
// and are used to protect the header file from being included
// by the same source file twice
// Define a namespace
namespace foo
{
// Define a class
class my_class
{
public:
my_class(int val)
: value_(val)
{}
int get_value() const
{
return value_;
}
void set_value(const int val)
{
value_ = val;
}
private:
int value_;
};
// Declare a function prototype
void bar(my_class& v);
}
#endif // MYHEADER_H
The above header file defines a namespace foo and in the namespace a class my_class and a function bar.
(The namespace is strictly not necessary for a simple program like this, but for larger projects it becomes more needed.)
Then the first source file, e.g. main.cpp:
#include <iostream>
#include "myheader.h" // Include our own header file
int main()
{
using namespace foo;
my_class my_object(123); // Create an instance of the class
bar(my_object); // Call the function
std::cout << "In main(), value is " << my_object.get_value() << '\n';
// All done
}
And finally the second source file, e.g. bar.cpp:
#include <iostream>
#include "myheader.h"
void foo::bar(foo::my_class& val)
{
std::cout << "In foo::bar(), value is " << val.get_value() << '\n';
val.set_value(456);
}
Put all three files in the same project, and build. You should now get an executable program that outputs
In foo::bar(), value is 123
In main(), value is 456
I prefer to provide a functional interface to global data.
.h file:
extern int get_entero();
extern void set_entero(int v);
.cpp file:
static int entero = 10;
int get_entero()
{
return entero;
}
void set_entero(int v)
{
entero = v;
}
Then, everywhere else, use those functions.
#include "the_h_file"
void function()
{
cout << get_entero() << endl;
//action1...;
}
void separated_function()
{
cout << get_entero() << endl;
//action2...;
}
int main( int argc, char *argv[] )
{
function();
separated_function();
cout<< get_entero() <<endl;
//something else with the mentioned variables...;
return 0;
}
If you do not plan to modify the variable, it is generally ok to make it global. However, it is best to declare it with the const keyword to signal the compiler that it should not be modified, like so:
const int ENTERO = 10;
If you are using multiple cpp files, also consider using a header file for your structures and function declarations.
If you are planning on modifying the variable, just pass it around in function parameters.

multiple definition of class

first of all I know that this question has been answered very often, but the answers didn't help me a lot...
That is the code which is causing the error.
#include "WayFinderClass.h"
WayFinderClass::WayFinderClass(int NavigationMapIndex) { ... };
int WayFinderClass::TotalNumberOfPoints(int point[100][100][2]) { ... };
int WayFinderClass::ConnectedWithXPoints(int point[100][100][2], int pointID) { ... };
void WayFinderClass::findWay(int start, int goal) { ... };
WayFinderClass.h :
#ifndef WAYFINDERCLASS_H_INCLUDED
#define WAYFINDERCLASS_H_INCLUDED
#include "NavigationMap.h"
class WayFinderClass {
public:
int finalWay[100];
int start;
int goal;
int alreadyCheckedInt[100];
void findWay(int start, int goal);
WayFinderClass(int NavigationMapIndex);
private:
int pointConnectedWith[100];
int wayProgress[100][100];
int numberOfPoints;
bool antsInProgress[100];
int TotalNumberOfPoints(int point[100][100][2]);
int ConnectedWithXPoints(int point[100][100][2], int pointID);
NewNavigationMap NavigationMap;
};
#endif // WAYFINDER_H_INCLUDED
And that is the error I get:
C:\{...} Line 3 multiple definition of 'WayFinderClass::WayFinderClass(int)'
So what am I supposed to do? I already tried to include the .h file but it didn't help me.
I also checked every other file whether the file WayFinderClass.cpp has been included a second time - but I found nothing.
You should not include source files (.cpp). Include headers instead.
Your problem was probably caused by including the source file in main.cpp as you said and then compiling it separately as well. In that case, functions defined in WayFinderClass.cpp would be defined again in main due to the inclusion and you can't have more than one definition for a function.

C++ Redefining variables of a namespace?

I've got two questions.
Question 1: Can someone provide an example of how to define/redefine a variable in a namespace. I've provided my own guess for you to base an your answer from.
// namespace.hpp
namespace example
{
static string version;
static int x;
}
And then in a .cpp how do I redefine those variables?
// namespace.cpp
namespace example
{
version = "0.1"; // ?????
x = 0; //???
}
Question 2: How would I attach a permanent class object onto a namespace from the same .hpp file? Something like this:
// namespace.hpp
class Idk
{
public:
int doThis();
}
namespace example
{
Idk idkObject;
}
The code above, when included multiple times (from different files) will replace the object, which will cause compilation errors. Once again, I need a permanent way to attach a object to a namespace its header file.
Instead of 'static', write 'extern' in the header file and include the data type in the variable definitions in the cpp file.
Question 1: You need to specify the type also
// namespace.cpp
namespace example
{
string version = "0.1"; // ?????
int x = 0; //???
}
Question 2: You shouldn't create a 'non-static' object in a header file irrespective of the namespace. You should just use static here also or else you should use extern in header file and define the variable inside a cpp file. {Note it's a little different with templatized classes}
// namespace.hpp
class Idk
{
public:
int doThis();
}
namespace example
{
static Idk idkObject;
}
// namespace.cpp
namespace example
{
Idk idkObject; // Default constructor
}

(C++) Linking with namespaces causes duplicate symbol error

For the past few days, I have been trying to figure out how to link the files for a CLI gaming project I have been working on. There are two halves of the project, the Client and the Server code.
The client needs two libraries I've made. The first is a general purpose game board. This is split between GameEngine.h and GameEngine.cpp. The header file looks something like this
namespace gfdGaming {
// struct sqr_size {
// Index x;
// Index y;
// };
typedef struct { Index x, y; } sqr_size;
const sqr_size sPos = {1, 1};
sqr_size sqr(Index x, Index y);
sqr_size ePos;
class board
{
// Prototypes / declarations for the class
}
}
And the CPP file is just giving everything content
#include "GameEngine.h"
type gfdGaming::board::functions
The client also has game-specific code (in this case, TicTacToe) split into declarations and definitions (TTT.h, Client.cpp). TTT.h is basically
#include "GameEngine.h"
#define TTTtar "localhost"
#define TTTport 2886
using namespace gfdGaming;
void* turnHandler(void*);
namespace nsTicTacToe
{
GFDCON gfd;
const char X = 'X';
const char O = 'O';
string MPhostname, mySID;
board TTTboard;
bool PlayerIsX = true, isMyTurn;
char Player = X, Player2 = O;
int recon(string* datHolder = NULL, bool force = false);
void initMP(bool create = false, string hn = TTTtar);
void init();
bool isTie();
int turnPlayer(Index loc, char lSym = Player);
bool checkWin(char sym = Player);
int mainloop();
int mainloopMP();
}; // NS
I made the decision to put this in a namespace to group it instead of a class because there are some parts that would not work well in OOP, and it's much easier to implement later on.
I have had trouble linking the client in the past, but this setup seems to work.
My server is also split into two files, Server.h and Server.cpp.
Server.h contains exactly:
#include "../TicTacToe/TTT.h" // Server needs a full copy of TicTacToe code
class TTTserv;
struct TTTachievement_requirement {
Index id;
Index loc;
bool inUse;
};
struct TTTachievement_t {
Index id;
bool achieved;
bool AND, inSameGame;
bool inUse;
bool (*lHandler)(TTTserv*);
char mustBeSym;
int mustBePlayer;
string name, description;
TTTachievement_requirement steps[safearray(8*8)];
};
class achievement_core_t : public GfdOogleTech {
public: // May be shifted to private
TTTachievement_t list[safearray(8*8)];
public:
achievement_core_t();
int insert(string name, string d, bool samegame, bool lAnd, int lSteps[8*8], int mbP=0, char mbS=0);
};
struct TTTplayer_t {
Index id;
bool inUse;
string ip, sessionID;
char sym;
int desc;
TTTachievement_t Ding[8*8];
};
struct TTTgame_t {
TTTplayer_t Player[safearray(2)];
TTTplayer_t Spectator;
achievement_core_t achievement_core;
Index cTurn, players;
port_t roomLoc;
bool inGame, Xused, Oused, newEvent;
};
class TTTserv : public gSserver {
TTTgame_t Game;
TTTplayer_t *cPlayer;
port_t conPort;
public:
achievement_core_t *achiev;
thread threads[8];
int parseit(string tDat, string tsIP);
Index conCount;
int parseit(string tDat, int tlUser, TTTplayer_t** retval);
private:
int parseProto(string dat, string sIP);
int parseProto(string dat, int lUser);
int cycleTurn();
void setup(port_t lPort = 0, bool complete = false);
public:
int newEvent;
TTTserv(port_t tlPort = TTTport, bool tcomplete = true);
TTTplayer_t* userDC(Index id, Index force = false);
int sendToPlayers(string dat, bool asMSG = false);
int mainLoop(volatile bool *play);
};
// Other
void* userHandler(void*);
void* handleUser(void*);
And in the CPP file I include Server.h and provide main() and the contents of all functions previously declared.
Now to the problem at hand
I am having issues when linking my server. More specifically, I get a duplicate symbol error for every variable in nsTicTacToe (and possibly in gfdGaming as well). Since I need the TicTacToe functions, I link Client.cpp ( without main() ) when building the server
ld: duplicate symbol nsTicTacToe::PlayerIsX in Client.o and Server.o
collect2: ld returned 1 exit status
Command /Developer/usr/bin/g++-4.2 failed with exit code 1
It stops once a problem is encountered, but if PlayerIsX is removed / changed temporarily than another variable causes an error
Essentially, I am looking for any advice on how to better organize my code to hopefully fix these errors.
Disclaimers:
-I apologize in advance if I provided too much or too little information, as it is my first time posting
-I have tried using static and extern to fix these problems, but apparently those are not what I need
Thank you to anyone who takes the time to read all of this and respond =)
You get error about duplicate definitions because that's what you have: each time a .cpp file includes TTT.h, a global bool PlayerIsX is defined (in the nsTicTacToe namespace, but still global). In this case, it's Server.cpp and Client.cpp that are including it.
One way to solve this could be to change the definitions into declarations by using extern, then doing the actual definition in a corresponding .cpp file (TTT.cpp, for instance).
In TTT.h:
namespace nsTicTacToe {
...
extern bool PlayerIsX;
...
}
In TTT.cpp:
#include "TTT.h"
bool nsTicTacToe::PlayerIsX;
and so on for the other definitions.
By the way, remember to have proper guard #ifdefs:
#ifndef __TTT_H
#define __TTT_H
... header contents
#endif // __TTT_H
Actually, extern IS what you need. You're probably just not realizing or remembering that you'll also have to define such variables in a cpp file.
header:
extern int somevar;
source:
int somevar = ?;
By putting all of your globals in the header you're making copies of them everywhere you include them, which is exactly what your compiler is bitching about.
You are essentially using globals, which is strongly not recommended in C++, but is sometimes necessary in C.
You could get it working with extern, but the "better" answer would be to wrap your globals in a state object of some sort.
struct State
{
GFDCON gfd;
const char X;
const char O;
string MPhostname, mySID;
board TTTboard;
bool PlayerIsX, isMyTurn;
char Player, Player2;
};
Create your state object in Main and pass it to each function that needs to know the state of the game system.
This will lead to much better code organization in the long run.
you could put the namespace nsTicTacToe part into it's own .cpp file, compile it separately and link it in.
You might also need a header file which just declares externs for the variables, and include that in you client and server .cpp files.