This question already has answers here:
error: Class has not been declared despite header inclusion, and the code compiling fine elsewhere
(9 answers)
Closed 7 years ago.
You could have forgot to include problemclass.h from the file where you are using ProblemClass.
You could have misspelled the name of ProblemClass either in its own header file or in the place where you are using it. This can be
hard to spot if it is a capitalization error such as writing
Problemclass or problemClass instead of ProblemClass.
You could have copy-pasted your inclusion guard #defines from one header file to another and then forgot to change the defined names.
Then only the first of those two included header files would take
effect.
You could have placed ProblemClass in a namespace A, in which case you must refer to ProblemClass as A::ProblemClass if you are referring
to it from outside the namespace A.
You may be using templates and not expecting two-phase lookup to work the way it does.
You could have misspelled the file name in your include. The compiler would not report an error on that if you also have an old
version of that file under the misspelled name.
You could have made ProblemClass a macro that only gets defined after you include problemclass.h, in which case what you see as
ProblemClass gets replaced by something else by the macro
preprocessor.
You could have defined ProblemClass in a header file other than problemclass.h and then problemclass.h actually defines something
else.
The above was taken from another similar question, I found the points useful but none actually solved my problem, stated hereunder:
I'm creating a natural language processor for a robot, giving the software various objects to represent real world items in its environment (Blocks world for now), one of the objects defined in Block:
/*
* Block.h
*
* Created on: 11 Mar 2015
* Author: Edward
*/
#ifndef BLOCK_HPP_
#define BLOCK_HPP_
#include "typedefinitions.h"
#include "dynamixel.h"
#include "BasicRobotFunctions.hpp"
class Block {
public:
bool grounded;
//TODO position is a deprecated variable, replace with distance from
//pos position;
int number;
int distance;
int object_brightness;
Block(BasicRobotFunctions basic);
virtual ~Block();
void setBrightness(int brightness);
void setGrounded(bool ground);
//void setPosition(int x, int y);
void setDistance(int number);
void setNumber(int number);
//pos getPosition();
int getNumber();
int getDistance();
bool getGrounded();
int getBrightness();
int lookAround(BasicRobotFunctions basic);
};
#endif /* BLOCK_H_ */
with source file:
/*
* Block.cpp
*
* Created on: 11 Mar 2015
* Author: Edward
*/
#include "Block.hpp"
#define DEFAULT_PORTNUM 3 // COM3
#define DEFAULT_BAUDNUM 1 // 1Mbps
Block::Block(BasicRobotFunctions basic) {
grounded = false;
number = Block::lookAround(basic);
}
Block::~Block() {}
void Block::setGrounded(bool ground){
grounded = ground;
}
/*
void Block::setPosition(int x, int y){
position.x = x;
position.y = y;
}*/
void Block::setDistance(int dist){
distance = dist;
}
void Block::setNumber(int num){
number = num;
}
bool Block::getGrounded(){
return grounded;
}
/*
pos Block::getPosition(){
return position;
}*/
int Block::getNumber(){
return number;
}
int Block::getDistance(){
return distance;
}
int Block::getBrightness(){
return object_brightness;
}
//TODO Arrange function to incorporate Turn() in BasicRobotFunctions
int Block::lookAround(BasicRobotFunctions basic){
int num = 0;
dxl_initialize(DEFAULT_PORTNUM,DEFAULT_BAUDNUM);
for(int i = 0;i<360;i++){
dxl_write_word(11,32,-255);
dxl_write_word(11,30,200);
basic.Step(1);
dxl_write_word(11,32,255);
dxl_write_word(11,30,100);
if(dxl_read_byte(100,32) >= dxl_read_byte(100,52)){
num++;
}
}
dxl_terminate();
return num;
}
void Block::setBrightness(int bright){
object_brightness = bright;
}
I am however receiving the following compilation error from the constructor and from the turnAround(BasicRobotFunctions) method:
In file included from Robot.hpp:11,
from BasicRobotFunctions.hpp:12,
from main.cpp:8:
Block.hpp:23: error: expected `)' before 'basic'
Block.hpp:35: error: 'BasicRobotFunctions' has not been declared
make.exe: *** [main.o] Error 1
Having checked my other classes utilizing objects as variables I get the same error.
In response to the points in the quote:
- BasicRobotFunctions.hpp is included
- the class name is spelt the same in all different instances mentioning it
- I didn't copy paste any inclusion guard
- I didn't use any namespaces in the project
- Nor am I using any templates
- the file name isn't misspelled in my include
- I haven't defined any macros in the program
- I made sure every class was defined in its own header file
Is there any other issue my system could possibly have, any mistake I'm making or simply anything I'm doing which is bad programming practice here?
The cause of your problem:
You have a header file circular dependency problem.
main.cpp includes BasicRobotFunctions.hpp
which includes Robot.hpp
which includes Block.hpp
which includes BasicRobotFunctions.hpp.
If your header files are properly guarded against multiple inclusion (which it seems that they are), Block.hpp won't see the definitions of BasicRobotFunctions.hpp because it is already in the middle of including it.
How to spot the problem:
The source of this problem is apparent in the compilation error message and in your Block.hpp file.
The compiler is reporting an error in Block.hpp, and it is describing line by line how it got to that file via inclusions. The source to your Block.hpp file makes it clear that it is trying to include BasicRobotFunctions.hpp.
The fix:
In your case, you can modify your method signatures in Block.hpp to use a (perhaps constant) reference to the BasicRobotFunctions type, and then forward declare the type. This allows you to eliminate the dependency on the BasicRobotFunctions.hpp header file. (Block.cpp would likely need to include both Block.hpp and BasicRobotFunctions.hpp.)
//...
#include "typedefinitions.h"
#include "dynamixel.h"
class BasicRobotFunctions; // Forward declaration
//...
Block(const BasicRobotFunctions &basic);
//...
int lookAround(const BasicRobotFunctions &basic);
//...
You may be able to avoid this problem in the future by minimizing what headers are required to allow your header file to compile. This means your header file should:
Use forward declarations to types that are used.
Use references to forward declared types.
You can check that your header file has minimized its dependencies by making sure it compiles by itself. I accomplish this by including the header file first in a corresponding source file, and then make sure the source file compiles.
// Foo.cpp
#include "Foo.hpp"
//...
Well you can put a forward declaration before the class as
class BasicRobotFunctions;
class Block {
public:
bool grounded;
//TODO position is a ...
but this kind of error means that the #include "BasicRobotFunctions.hpp"
don't declare the BasicRobotFunctions. It's possible a trouble with code guards?
The circular inclusion can be solved using the forward declaration, putting correct guards in headers and moving some includes to source files.
Related
I'm new to C++ and trying to make a map that all the source files will be able to access. Here is a simplified version of the problematic code. Every header file has a header guard, I just didn't type them here.
// main.cpp
#include "client.hpp"
int main(void){
init();
search();
}
// util.cpp
#include "util.hpp"
std::map<int, STUDENT_TYPE> dataBase;
init(){
dataBase[0] = STUDENT_TYPE(14, 4.0);
// more students....
}
// util.hpp
#include <map>
struct STUDENT_TYPE{
int age;
int grade;
STUDENT_TYPE(int age, int grade) : age(age), grade(grade){}
};
extern std::map<int, STUDENT_TYPE> dataBase;
// client.cpp
#include "client.hpp"
void search(){
std::cout << dataBase[0].grade << std::endl;
}
// client.hpp
#include "util.hpp"
void search();
The problem is that the compiler failed to build at the search function. It gives a big chain of errors. The last error or the cause of all the error is that the constructor of STUDENT_TYPE require 2 fields while given 0. I suspect that client can't access the STUDENT_TYPE struct inside the dataBase. I don't how to fix it or exactly how it happened. I just want a big table of students that all the files in the program can access.
The compiler is telling you exactly what's wrong. Your student type doesn't have a default constructor and it's being used.
Why is it being used?
Because map::operator [] will create a default constructed instance to return if an entry doesn't yet exist for that key. Even if this never happens, the compiler still has to compile that branch and it can't here.
Two ways to fix:
Give your student type a meaningful default.
Don't use map::operator[]. Instead use map::find.
First solution; don't have a global data structure. There is normally no need at at all to have such a thing.
Secondly, understand what header guards do - they prevent the body of a header file being included in the same translation unit. They have no effect if the header file is included in multiple .cpp files.
Thirdly, when you post questions about problems here, post the full text of the error messages you are getting.
I'm new to doing structs, so please bear with me if this turns out to be a dumb question. I have one header file and four .cpp files that all include it. I have a struct called ToDoLista and it has string nameIt and int DeadLine. Then I have the things whose type name I don't know that are like, the Soccer and DropOffMax and stuff.
ToDoLista Soccer, DropOffMax, CookDinner;
Soccer.DeadLine=6;
Soccer.nameIt="SOCCER";
//and so on, for a total of six, 3 ints and 3 strings definitions.
This struct seems to be finnicky if I try to move it around because if it's in the header it's included three times and it wont run due to 'multiply defined' whatever. If I put it in one of my three non-main cpp files, it seems that the struct won't work because some of it has to be defined in main(). So now it's in my main cpp file, but I have functions that use these values, and those functions are in my non-main cpp files, which as far as I know compile before the main one. To get around that, I put the struct declaration in the header, and the definitions in my main (I may have mis-worded that) AND THEN I say 'okay, run the function 'CheckItTwice'.
//MAIN
Soccer.DeadLine=6;
//and so on for all six, like before.
//ok, NOW run the fx.
CheckItTwice(Soccer.Deadline, Soccer.nameIt);
The issue here is that if I tell CheckItTwice to say, cout the string, or the int, it runs the program without errors, but returns nothing in the console where the cout should be, because apparently they haven't been defined yet, as far as the function is concerned. Why is this/do you know a way around this?
In order to avoid the "defined multiply" errors you need to define your struct in a header file, and put a #pragma once or #ifndef...etc block at the top. See this here.
Include the header file in any implementation (cpp) file you plan to use the struct in.
The line
ToDoLista Soccer, DropOffMax, CookDinner;
declares three instances of the struct ToDolista, called Soccer, DropOffMax, and CookDinner. They are not types, they are instances of a type, that type being ToDolista.
I can't comment on the contents of CheckItTwice() as you didn't provide them, but look here for guidance on using cout. You might want to consider passing the struct as one argument to this method, preferrably as a const reference.
Define the struct in your header and #include that header in the cpp files. In the header try adding
#pragma once
at the top of your header file. This is a Microsoft specific extension - documented here
The more portable version is to add
#ifndef _SOME_DEF_
#define _SOME_DEF_
struct ToDoLista {
string namit;
string project;
int status;
int speed;
int difficulty;
int priority;
int deadline;
}
#endif // _SOME_DEF_
Be sure to remove struct definition from the .cpp file.
I got this issue resolved using something I saw while searching desperately online: extern. it seems that if I put the declaraction in the header, the definition in a cpp, and then declare the object again in another cpp but with 'extern' before it, it works like a charm as far as keeping the values from the original definition.
Header.h
struct ToDoLista{
string namit;
string project;
int status;
int speed;
int difficulty;
int priority;
int deadline;
};
Side.cpp
ToDoLista Pushups, Tumblr, Laundry, CleanRoom, CleanHouse, Portfolio;
void CheckItTwice(int staytus, string name){
if(staytus==1){//not on the list
staytus==2;
cout << "hurry up and" << name << " okay?" << endl;
Main.cpp
extern ToDoLista Pushups, Tumblr, Laundry, CleanRoom, CleanHouse, Portfolio;
Pushups.namit = "Push Ups";
Pushups.status = 1;
Pushups.speed = 0;
Pushups.difficulty = 0;
Pushups.priority = 0;
Pushups.project = "Get Fit";
Pushups.deadline = 20131102;
CheckItTwice(Pushups.status,Pushups.namit);
This works for me, and I hope this 'answer' helps someone else.
I'm making my first attempt at unit testing in C++, and I haven't used C++ in a number of years (I'm mainly a C# coder at the moment). It seems like I'm making a right pig's ear of it - I hope someone can steer me back onto the righteous path. I'm just getting started here and would really like to be implementing these tests using the best practice possible, so any and all comments are welcome, even though I'm most concerned with my linker error at present.
So, I have an overall solution "Technorabble", with sub-projects "CalibrationTool" and "CalibrationToolUnitTests".
CalibrationTool has a MathUtils.h file:
#ifndef __math_utils__
#define __math_utils__
#include "stdafx.h"
#include <vector>
namespace Technorabble
{
namespace CalibrationTool
{
double GetDoubleVectorAverage(std::vector<double> v)
{
double cumulativeValue = 0;
for(std::vector<double>::iterator iter = v.begin(); iter != v.end(); ++iter)
{
cumulativeValue += *iter;
}
return cumulativeValue / v.size();
}
}; // end namespace CalibrationTool
}; // end namespace Technorabble
#endif // !__math_utils__
(But no .cpp file as I was having all kinds of (somewhat similar) issues getting my template function working - so I ended up defining that inline).
Moving on to the Unit Tests project, I have a main.cpp:
#include "MathUtilsTest.h"
void RunMathUtilsTests();
int main()
{
RunMathUtilsTests();
// Other class tests will go here when I have things to test
}
void RunMathUtilsTests()
{
MathUtilsTest* mathUtilsTest = new MathUtilsTest();
mathUtilsTest->RunTests();
delete mathUtilsTest;
}
Finally, the header and cpp for the MathUtilsTest class, again, fairly simple:
.h:
#ifndef __MATH_UTILS_TEST__
#define __MATH_UTILS_TEST__
#include "CalibrationToolUnitTestsLogging.h"
#include "..\CalibrationTool\MathUtils.h"
class MathUtilsTest
{
public:
MathUtilsTest();
~MathUtilsTest();
bool RunTests();
private:
bool GetDoubleVectorAverageTest();
}; // end class MathUtilsTest
#endif
.cpp:
#include "MathUtilsTest.h"
#include <sstream>
bool MathUtilsTest::RunTests()
{
return GetDoubleVectorAverageTest();
}
MathUtilsTest::~MathUtilsTest()
{
}
MathUtilsTest::MathUtilsTest()
{
}
bool MathUtilsTest::GetDoubleVectorAverageTest()
{
bool passed = true;
std::vector<double> values;
for (int i = 1; i < 23; i++)
{
values.push_back(i);
}
// vector becomes: 1, 2, 3, 4, .....20, 21, 22. Average is 11.5
double expectedAverage = 11.5;
double calculatedAverage = Technorabble::CalibrationTool::GetDoubleVectorAverage(values);
if (calculatedAverage != expectedAverage)
{
std::ostringstream s;
s << calculatedAverage;
std::string avgString = s.str();
CalibrationToolUnitTestsLogging::Write("Failed MathUtilsTest.GetDoubleVectorAverageTest: " + avgString);
passed = false;
}
else
{
CalibrationToolUnitTestsLogging::Write("Passed MathUtilsTest.GetDoubleVectorAverageTest");
}
return passed;
}
This all seemed fine to me, I'm protecting my header with #ifndef, etc. But I'm still getting the following errors:
1) error LNK1169: one or more multiply defined symbols found
2) error LNK2005: "double __cdecl Technorabble::CalibrationTool::GetDoubleVectorAverage(class std::vector >)" (?GetDoubleVectorAverage#CalibrationTool#Technorabble##YANV?$vector#NV?$allocator#N#std###std###Z) already defined in main.obj C:_SVN\Technorabble\Windows Software\CalibrationToolUnitTests\MathUtilsTest.obj
How can this be? Can anyone spot where it's going wrong?
Functions defined in headers should be marked as inline:
inline double GetDoubleVectorAverage(std::vector<double> v)
{
}
If it's longer than a couple of lines, consider moving it to an implementation file.
pragmas or include guards don't protect against multiple definitions.
Note that you should pass v by const reference rather than by-value.
You are defining a function GetDoubleVectorAverage in a header. This means that it will be defined in every translation unit (i.e. every source file) that includes that header. If your program contains more than one such translation unit, then you'll have more than one definition - which isn't allowed.
Solutions are:
Add inline to the function definition, to relax this rule and allow multiple identical definitions; or
Move the function definition into a source file, and only declare it in the header.
I'm protecting my header with #ifndef
That only prevents the header from being included more than once within the same translation unit. It doesn't prevent inclusion from more than one unit.
Also, you shouldn't use a reserved name like __math_utils__ as a header guard, even if the internet is littered with examples of dodgy code doing that.
I was having all kinds of (somewhat similar) issues getting my template function working
Templates usually need to be defined in header files, to make the definition available at the point of use. Function templates are implicitly inline, but normal functions (like this one) aren't.
When I compile the program I am working on I get:
expected initializer before 'class'
error in my Class.h file. I looked up the error message on the internet, but couldn't find the exact error, although similar errors seem to be caused by missing semicolons but I don't see why I need one. This is the code the error points to, I have no other functions or classes before it.
class Account
{
public:
double dAccountBalance;
double dAccountChange(double dChange);
};
In the Class.cpp file the double dAccountChange(double dChange) function is defined. I don't think this is where the error is coming from but this is the code;
double Account::dAccountChange(double dChange)
{
dAccountBalance += dChange;
return 0.0;
}
When I change the code in Class.h to look like this,
;
class Account
{
public:
double dAccountBalance;
double dAccountChange(double dChange);
};
it doesn't generate an error message, but I can't work out why I need the semicolon before it as the only code I have before it are the following pre-processor lines.
#ifndef CLASS_H_INCLUDED
#define CLASS_H_INCLUDED
Any ideas on why the error is generated?
Most likely, in the header file you include immediately before class.h, you'll have something like:
class xyzzy {
int plugh;
}
without the closing semi-colon. That will make your code sequence:
class xyzzy {
int plugh;
}
class Account
{
public:
double dAccountBalance;
double dAccountChange(double dChange);
};
which is clearly invalid. Inserting a semi-colon in class.h before the first line will fix it, but it's clearly the wrong place to put it (since it means every header file you include immediately after that one would need a starting semicolon - also, it's part of the definition in the first header and should be there).
Now that may not be the exact code sequence but it will be something very similar, and the underlying reason will be a missing piece of text in the previous header.
You should go back and put it in the earlier include file.
For example, consider:
include1.h:
class xyzzy {
int plugh;
}
include2.h:
class twisty {
int little_passages;
};
main.cpp:
#include "include1.h"
#include "include2.h"
int main (void) {
return 0;
}
Compiling this produces:
include2.h:3: error: multiple types in one declaration
but placing the semicolon at the end of include1.h (or start of include2.h though we've already established that's not a good idea) will fix it.
The problem is in one of the other headers, one that you #include ahead of class.h.
If you show us the top of your main cpp file, it might give a clue.
I have a class called File that is defined (along with other classes) in the header "dmanager1.h". In the "dmanager1.cpp" file (implementation for the dmanager1.h file), when I list the headers in one order I get an error when trying to compile along with my main.cpp (main.cpp is empty except for the header call and an empty "int main()"...basically I'm just testing the class .h and .cpp files)... If I switch the headers around in the dmanager1.cpp file I get no errors. I don't understand what is happening. The error I'm getting is:
error: 'File' does not name a type
I get said error when I have my header's ordered in my "dmanager1.cpp" as follows:
#include "dmanager1.h"
#include <iostream>
#include <cstring>
If I switch the header's around to:
#include <iostream>
#include <cstring>
#include "dmanager1.h"
...I don't get the compilation error. Is the first order getting parsed funny? Any thoughts would be greatly appreciated.
EDIT: Added part of the header in question...
#ifndef _dmanager1_h
#define _dmanager1_h
//--------------------
// Forward References
//--------------------
// Node_L, Node_T, and Sector are defined in File: dmanager1a.h
class Node_L;
class Node_T;
class Sector;
class File
{
public:
// Default Constructor
//File();
// Constructor: Allowing "name", "size", and/or "permissions" to be set
// Permissions set to default of 0 == read and write
File(const char * & name, float size = 0, int permissions = 0) : timestamp(11223333) {};
// Default Destructor
~File();
//returns an int corresponding to the date modified (mmddyy)
int get_date_mod(void) const {return timestamp;}
// Return's current level of permission on the File: 0 = read/write, 1 = read only
int get_permission(void) const {return permission;}
// Set's Permission to "level": 0 = read/write, 1 = read only
int set_permission(int level);
private:
// Data members
char * name;
float size_OA;
//function used to update "date modified"
void update_timestamp(void);
// Current permission level of the file: 0 = read/write, 1 = read only
int permission;
//value modified by update_timestamp() and the value returned by get_date_mod(). Date file last edited.
int timestamp;
};
Most likely your dmanager1.h header needs something that iostream or cstring define.
As a result, it doesn't get parsed correctly, and the compiler doesn't understand the declaration of your File class.
If you post your dmanager1.h file, you'll be able to get a more detailed answer.
Make sure that each of your headers is completely self-sufficient. It needs to #include headers for everything that it uses and not assume that they will be included by something else. Every header should work even if it is the only header that a .c file includes.
I'm betting that your dmanager1.h header is using something from the standard library and you aren't including the header that it needs. Swapping the header appears to fix the problem, but it's only working by coincidence.
One diagnostic test you can do is to create a .c file that contains nothing but the line #include "dmanager1.h". Try to compile it. If the compiler throws an error, it should provide hints as to which additional headers need to be included.
Update: I can compile using the initial portion of the header that you posted using g++ -Wall and I get no errors or warnings at all. Please post a sample that reproduces the problem.