This is really puzzling me. For some reason I get a
"c1 not declared in this scope"
error from the compiler. I am usig Mingw with Code::Blocks. I would assume global variables are global to the program? Am I wrong? TYIA -Roland
// main.h
#include <iostream>
#include "classone.cpp"
#include "classtwo.cpp"
extern AnotherClass c2;
extern TheClass c1;
----------
// main.cpp
#include "main.h"
AnotherClass c2;
TheClass c1;
int main()
{
c1.function5();
c2.function2();
return 0;
}
----------
//classone.h
#include "main.h"
class AnotherClass {
`
public:
void function2();
void function3();
private:
int varone;
int vartwo;
};
----------
// classone.cpp
#include "classone.h"
void AnotherClass::function2() {
std::cout << "Function 2 Check\n";
}
void AnotherClass::function3() {
std::cout << "Function 3 Check";
}
----------
// classtwo.h
#include "main.h"
class TheClass {
public:
void function4();
void function5();
};
----------
// classtwo.cpp
#include "classtwo.h"
void TheClass::function4() {
c1.function2();
std::cout << "Function 2 Check\n";
}
void TheClass::function5() {
std::cout << "Function 3 Check";
}
It's quite silly to include .cpp files like that - only include headers.
Anyway, change main.h to this:
#include <iostream>
extern AnotherClass c2;
extern TheClass c1;
Add this to main.cpp:
AnotherClass c2;
TheClass c1;
Then include main.h in each file which needs it, like this:
// classtwo.cpp
#include "classtwo.h"
#include "main.h"
void TheClass::function4() {
c1.function2();
std::cout << "Function 2 Check\n";
}
void TheClass::function5() {
std::cout << "Function 3 Check";
}
Also, you need include guards if you don't have those already.
You need to include the class declarations in your .cpp files if you want to compile all the code in a single file. Inside classtwo.cpp insert #include "classtwo.h" and do the same for classone at the top of both files.
Standard practice is to separate the class code from the client code, so you should compile the classes into a library and link it to the main program.
Your main .h needs to include the .h files of the 2 classes, for it to work. You do not (and should not ) need to include the .cpp files.
Related
How can I define an integer in a header file so that each cpp file which includes the header will have static const int id=0 while giving the ability to cpps to redefine it with other value.
I tried to used weak symbol but couldn't make it work.
If you are ok with preprocessor definitions you could do this:
// header.h
#ifndef CLASSID
#define CLASSID 0
#endif
static int id=CLASSID;
// class.cpp
#define CLASSID 1
#include "header.h"
This way a source file may override the default, but may also omit it, which is the sort of weak approach you mentioned.
Here's another solution that uses static variables:
// log.h
#ifndef LOG_H
#define LOG_H
#include <iostream>
#define SETLOGID(v) static logidsetter _logidsetter(_logid, v);
#define LOG(v) std::cout << "id: " << _logid << ": " << (v) << std::endl;
class logidsetter
{
public:
logidsetter(int &id, int val)
{
id = val;
}
};
static int _logid = 0;
#endif
// myclass.h
class myclass
{
public:
myclass();
void run(void);
};
// myclass.cpp
#include "log.h"
#include "myclass.h"
SETLOGID(42)
myclass::myclass()
{
LOG("myclass::cons");
}
void myclass::run(void)
{
LOG("myclass::run");
}
// main.cpp
#include "myclass.h"
#include "log.h"
SETLOGID(1)
int main()
{
myclass mc;
LOG("here's main");
mc.run();
}
The log header defines the static int _logid and provides the macro SETLOGID and the class idsetter. The cpp file may use SETLOGID to redefine the static value. This is done with an instantiation of the class idsetter along with the address of _logid and the desired value. The trick allows to bypass C++'s One Definition Rule.
The output looks like:
id: 42: myclass::cons
id: 1: here's main
id: 42: myclass::run
So I've done extensive googling and searching on StackOverflow and am unable to find a solution despite several answers with this exact issue.
I am trying to create a test class in an external file called Fpc5.cpp
It's contents are:
Fpc5.cpp
#include "stdafx.h"
#include "Fpc5.h";
#include <iostream>
using std::cout;
class Fpc5 {
int bar;
public:
void testMethod();
};
void Fpc5::testMethod() {
cout << "Hey it worked! ";
}
and my main .cpp file:
Test.cpp
// Test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
//#include "Fpc5.cpp"
#include "Fpc5.h";
using std::cout;
using std::cin;
using std::endl;
int main()
{
cout << "Hello" << endl;
Fpc5 testObj;
testObj.testMethod();
system("pause");
return 0;
}
all the answers I've read indicate this is caused becaused I used to be including the class in the main file itself which is why I created a header file
Fpc5.h
#pragma once
void testMethod();
This changed the error, but still did not fix the issue. Currently my Test.cpp does not recognize a Fpc5 class. I've also tried adding the Fpc5.cpp and Fpc5.h in stdafx.h and that still does not resolve the issue.
stdafx.h
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
// TODO: reference additional headers your program requires here
//#include "Fpc5.cpp"
#include "Fpc5.h"
I'm sure this a simple syntax/conceptual understanding error, but I'm quite new to c++ and am not sure what is wrong.
This is definition of your class and it must be in Fpc5.h
class Fpc5 {
int bar;
public:
void testMethod();
};
Then, you have Fpc5.cpp where you implement methods of the class:
#include "Fpc5.h" // Compiler needs class definition to compile this file!
void Fpc5::testMethod()
{
}
And then you can use Fpc5 class in Test.cpp
#include "Fpc5.h"
int main()
{
Fpc5 foo;
foo.testMethod();
return 0;
}
As an alternative you can pack everything into Test.cpp
Move the definition of your class:
class Fpc5 {
int bar;
public:
void testMethod();
};
to the header file, "Fpc5.h".
Implement the methods to "Fpc5.cpp".
This question already has answers here:
Resolve build errors due to circular dependency amongst classes
(12 answers)
Closed 7 years ago.
Please see my previous post here:
Undefined type error even with forward declaration
I moved the definitions to cpp files and I still face the issue. Any ideas why? My files look like this:
Header1.hpp
#ifndef HEADER1_HPP
#define HEADER1_HPP
namespace sample_ns
{
class sample_class{
public:
static int getNumber();
static void print();
};
}
#endif
Header2.hpp
#ifndef HEADER2_HPP
#define HEADER2_HPP
namespace sample_ns
{
class sample_class2{
public:
sample_class2();
int getNumber2();
};
}
#endif
Source1.cpp
#include "Header1.hpp"
#include "Header2.hpp"
#include "stdafx.h"
#include <iostream>
namespace sample_ns
{
int sample_class::getNumber()
{
sample_class2 obj;
return obj.getNumber2();
}
void sample_class::print()
{
std::cout << "Print utility function" << std::endl;
}
}
Source2.cpp
#include "Header2.hpp"
#include "Header1.hpp"
#include "stdafx.h"
#include <iostream>
namespace sample_ns
{
sample_class2::sample_class2()
{
sample_class::print();
}
int sample_class2::getNumber2()
{
sample_class::print();
return 5;
}
}
In my main I call it as:
std::cout << sample_ns::sample_class::getNumber() << std::endl;
I get 'sample_class2' : undeclared identifier. I tried adding class sample_class2; but that still gives me error
EDIT:
my main file:
#include "stdafx.h"
#include <iostream>
#include "Header1.hpp"
int _tmain(int argc, _TCHAR* argv[])
{
std::cout << "hello" << std::endl;
std::cout << sample_ns::sample_class::getNumber() << std::endl;
return 0;
}
The best practice for declaring classes and namespaces in header and cpp files is using structure likes below:
Header1.hpp
#ifndef HEADER1_HPP
#define HEADER1_HPP
#include "Header2.hpp"
#include <iostream>
namespace sample_ns
{
class sample_class{
public:
static int getNumber();
static void print();
};
}
#endif
Source1.cpp
#include "Header1.hpp"
namespace sample_ns
{
int sample_class::getNumber()
{
sample_class2 obj;
return obj.getNumber2();
}
void sample_class::print()
{
std::cout << "Print utility function" << std::endl;
}
}
So by including in header files and using ifndef you become sure that circular dependencies will not occure.
Recently I've been learning how to create methods within classes so that I only have to write a method once and for each of that class I instantiate I can call the one method and it will work only on the variables of the object that called it, I know how to do this when only using main.cpp and no headers however I am confused on how I should be writing this when I use a class header and cpp.
I have a sample of code similar to what I want to achieve:
#include <iostream>
using namespace::std;
class Object
{
public:
int stuff;
void manageStuff();
Object();
};
void Object::manageStuff()
{
stuff++;
}
Object::Object() : stuff(0) {}
Object object1, object2;
int main() {
for (int i = 0; i < 10; i++)
{
object1.manageStuff();
object2.manageStuff();
cout << object1.stuff << "\n";
cout << object2.stuff << "\n";
}
}
This works fine and allows me to have two instances of Object and a method that works independently for each instance, this is my current project:
main.cpp:
#include <iostream>
#include "Test.h"
using namespace std;
int main()
{
Test test;
for (int i = 0; i < 10; i++)
{
test.count(); // Here's my error "undefined reference to Test::count"
}
return 0;
}
Test.cpp
#include <iostream>
#include "Test.h"
using namespace std;
Test::Test()
{
//ctor
}
Test::~Test()
{
//dtor
}
Test.h
#include <iostream>
#ifndef TEST_H
#define TEST_H
class Test
{
public:
Test();
virtual ~Test();
void count();
int counter();
};
#endif // TEST_H
and finally TestFunctions.h
#include <iostream>
#include "Test.h"
#ifndef TESTFUNCTIONS_H_INCLUDED
#define TESTFUNCTIONS_H_INCLUDED
void Test::count()
{
Test::counter++;
std::cout << Test::counter;
}
#endif // TESTFUNCTIONS_H_INCLUDED
I'm sure that there will be something that's very obviously wrong to a more seasoned programmer and I'm about to look a bit thick but any help would be greatly appreciated
Thanks!
I would suggest getting rid of TestFunctions.h, and adding the implementation of Test::count() to Test.cpp. Currently, the TestFunctions.h header is not included anywhere, so you have no access to the definition from main.
You defined (i.e. implemented) Test::count() in a header file (TestFunctions.h), but you never included it anywhere so the code there is not compiled.
You should change it to be in a .cpp file, compile it and link it with the other source files. There's no reason why not to place it in Test.cpp.
Rename TestFunctions.h into TestFunctions.cpp, make it compiled same way as main.cpp and linked.
Alternatively, include TestFunctions.h somewhere, e.g. main.cpp
I'm in the process of trying to make a game-in-progress more modular. I'd like to be able to declare a single array of all the room_t objects in the game (room_t rooms[]), store it in world.cpp and call it from other files.
The truncated code below does not work, but it's as far as I've gotten. I think I need to use extern but have not been able to find a method that works correctly. If I try and declare the array in the header file, I get a duplicate object error (as each file calls world.h, I'd assume).
main.cpp
#include <iostream>
#include "world.h"
int main()
{
int currentLocation = 0;
cout << "Room: " << rooms[currentLocation].name << "\n";
// error: 'rooms' was not declared in this scope
cout << rooms[currentLocation].desc << "\n";
return 0;
}
world.h
#ifndef WORLD_H
#define WORLD_H
#include <string>
const int ROOM_EXIT_LIST = 10;
const int ROOM_INVENTORY_SIZE = 10;
struct room_t
{
std::string name;
std::string desc;
int exits[ROOM_EXIT_LIST];
int inventory[ROOM_INVENTORY_SIZE];
};
#endif
world.cpp
#include "world.h"
room_t rooms[] = {
{"Bedroom", "There is a bed in here.", {-1,1,2,-1} },
{"Kitchen", "Knives! Knives everywhere!", {0,-1,3,-1} },
{"Hallway North", "A long corridor.",{-1,-1,-1,0} },
{"Hallway South", "A long corridor.",{-1,-1,-1,1} }
};
Just add extern room_t rooms[]; in your world.h file.
world.h
extern room_t rooms[];
The problem is that you're trying to reference a variable you've declared in the .cpp file. There's no handle on this outside of the scope of this file. In order to fix this, why not declare the variable in the .h file but have an Init function:
room_t rooms[];
void Init();
Then in the .cpp
void Init() {
// create a room_t and copy it over
}