This question already has an answer here:
g++ error: ‘vec’ does not name a type [duplicate]
(1 answer)
Closed 8 years ago.
Ok so I am trying to map some of my member functions in the .h file this is to be able to use the map when I implement the code. However, after hours I have gotten nowhere so I would like suggestions or if anyone knows how to implement this. For reference these are the errors.
./Assembler.h:51:2: error: C++ requires a type specifier for all declarations
functions["load"] = load;
^~~~~~~~~
./Assembler.h:51:12: error: size of array has non-integer type 'const char [5]'
functions["load"] = load;
^~~~~~
./Assembler.h:51:2: error: duplicate member 'functions'
functions["load"] = load;
^
As for my header file it with the problem coming from the map:
#include <vector>
#include <iostream>
#include <map>
#include <string>
#include <fstream>
using namespace std;
class Assembler {
public:
Assembler(string filename);//Argument will be passed from the os.cpp file
void parse();// Will go through the a file to output the .o file
void load();
void loadi();
void store();
void add();
void addi();
void addc();
void addci();
void sub();
void subi();
void subc();
void subci();
void ander();
void andi();
void xorer();
void xori();
void negate();
void shl();
void shla();
void shr();
void shra();
void compr();
void compri();
void getstat();
void putstat();
void jump();
void jumpl();
void jumpe();
void jumpg();
void call();
void ret();
void read();
void write();
void halt();
void noop();
private:
typedef void (*function)();
map<string, function> functions;
functions["load"] = load;
fstream in, out; //One will be the .s file while the other will be the .o file
string opcode;
int rd, rs, constant, addr, machcode; //Different parts of the instruction
};
Any help or suggestions would be appreciated. Thanks
Only static const integral data members can be initialized within a class. You probably need to move functions["load"] = load; to a function's definition.
And also, you need to change them to:
typedef void (Assembler::*function)();
...
functions["load"] = &Assembler::load;
Within C++ class declaration, you cannot have member initialiser or executable statement, Have this one
functions["load"] = load;
within constructor
Take a look at your class declaration: everything's compiling fine except
functions["load"] = load;
This is an assignment and initializes the functions map with something. That is not allowed in the declaration which is a "contract" (in the case of an interface) or "explanation" of how your class is composed and what methods/members has.
The right spot to put such an initialization is in your constructor's definition (i.e. in the part of the code that actually contains the code of your methods, specifically when the object gets created if you intend to initialize stuff.. i.e. the constructor).
Related
I'm trying to use emscripten to compile a c++ class and expose bindings. I'm running into an error from the compiler.
#include <emscripten/bind.h>
#include <emscripten/emscripten.h>
using namespace emscripten;
class MyClass {
private:
int _year;
int _month;
int _day;
public:
MyClass() { }
MyClass(int year, int month, int day);
int getMonth();
void setMonth(int);
int getYear();
void setYear(int);
int getDay();
void setDay(int);
bool isLeapYear();
int daysInMonth();
void increment();
void decrement();
};
EMSCRIPTEN_BINDINGS(my_sample_class) {
class_<MyClass>("MyClass")
.constructor<>()
.constructor<int, int, int>()
.function("getMonth", &MyClass::getMonth)
.function("increment", &MyClass::increment)
.function("decrement", &MyClass::decrement)
.property("year",&MyClass::getYear, &MyClass::setYear )
//.property("month", &MyClass::getMonth, &MyClass::setMonth )
//.property("day",&MyClass::getDay, &MyClass::setDay )
;
}
The compiler has no problems with the constructors or the function binding. I run into a problem with the property binding. I only have one uncommented to minimize the errors that I get back (they are just repeats of the same error but for different lines). Here are the errors that I'm getting back.
In file included from MyDate.cpp:1:
In file included from ./MyDate.h:2:
emscripten/bind.h:1393:26: error: implicit instantiation of undefined template 'emscripten::internal::GetterPolicy<int (MyClass::*)()>'
auto gter = &GP::template get<ClassType>;
^
./MyDate.h:37:6: note: in instantiation of function template specialization 'emscripten::class_<MyClass, emscripten::internal::NoBaseClass>::property<int (MyClass::*)(), void (MyClass::*)(int)>' requested here
.property("year",&MyClass::getYear, &MyClass::setYear )
^
emscripten/bind.h:569:16: note: template is declared here
struct GetterPolicy;
^
emscripten/bind.h:1399:33: error: implicit instantiation of undefined template 'emscripten::internal::GetterPolicy<int (MyClass::*)()>'
TypeID<typename GP::ReturnType>::get(),
^
emscripten\1.38.21\system\include\emscripten/bind.h:569:16: note: template is declared here
struct GetterPolicy;
^
2 errors generated.
shared:ERROR: compiler frontend failed to generate LLVM bitcode, halting
I've looked up binding examples and it appears I'm using the right syntax. Does any one have any idea of what I might be doing wrong?
Found the problem!
The getter functions must be marked as const to avoid these errors.
EX:
int getMonth() const;
i'm trying to implement a clone of the json serialization library nlohmann::json as a learning experience, and i'm having trouble with the interface for user defined (json<->User type) conversion.
Basically i want the user to be able to overload two function: to_json(json&, const Type&) and from_json(const json&, Type&). Then the library will use overload resolution to call theses function in the templated operator= and one argument constructor.
It works fine when i'm just defining theses function directly but when i try to make a template definition for multiple types (in this example the class S) the linker can't find the definition.
I've tried to explicitly instantiate the function for individual instances of the templated class although i would prefer avoiding having to do that in the final product.
I'm guessing it has to do with the fact that templated function don't have the same signature than free function, but i don't see what i can do to make it work. What am i missing ? I also couldn't find result on google so is it a documented pattern or an anti pattern ?
Thanks you. Below i tried to minimize my problem in one short example.
Class.hpp
#pragma once
#include <cstdio>
template<size_t i>
class S {
size_t n = i;
};
template<size_t i>
void g(const S<i>& s) {
printf("S<%u>\n", i);
}
Class.cpp
#include "Class.hpp"
template void g<10>(const S<10>&); // <-- Even with explicitly instanciation
void g(const bool& b) {
printf("%s\n", b ? "true" : "false");
}
main.cpp
#include "Class.hpp"
template<typename T>
void f(T t) {
extern void g(const T&);
g(t);
}
int main(int, char**) {
S<10> s;
//f(s); <-- linker error: void g(class S<10> const &) not found.
f(false);
}
The name lookup for g in g(t) call stops as soon as it finds extern void g(const T&); declaration; it never sees the declaration of the function template. So the compiler generates a call to a regular non-template function named g taking const S<10>&. But no such function is defined in your program - hence linker error.
I am trying to use a timer to repeatedly change the PWM Output over time to have a smooth transition when the brightness changes. I keep getting this error when trying to compile the code:
/Users/jt/Documents/Arduino/libraries/SingleColorLight/SingleColorLight.cpp: In constructor 'CSingleColorLight::CSingleColorLight(int)':
/Users/jt/Documents/Arduino/libraries/SingleColorLight/SingleColorLight.cpp:13:58: error: cannot convert 'CSingleColorLight::DimmerCallback' from type 'void (CSingleColorLight::)(void*)' to type 'void ()(void)'
ets_timer_setfn(&Dimmer, this->DimmerCallback, NULL);
Here is my code:
class CSingleColorLight {
private:
int pin;
int intensitySetPoint;
int intensityActual;
int percentageBuffer;
ETSTimer Dimmer;
int dimmerCount;
public:
CSingleColorLight(int _pin);
bool setIntensity(int _intensity);
int getIntensity();
bool getStatus(void);
bool setStatus(bool _status);
void DimmerCallback(void*);
};
and in the cpp file:
void CSingleColorLight::DimmerCallback(void*) {
if(dimmerCount>0){
dimmerCount--;
intensityActual++;
} else if(dimmerCount<0){
dimmerCount++;
intensityActual--;
} else {
ets_timer_disarm(&Dimmer);
}
analogWrite(pin, percentageToTime[intensityActual]);
return;
}
It asks for a pointer, right? Any idea how to fix this?
Thanks a lot!
If you want DimmerCallback to take a void* argument, then you need to name it, like
void CSingleColorLight::DimmerCallback(void* x)
but you are not using the void* in the code. It looks like you should just get rid of it, so it would be
void CSingleColorLight::DimmerCallback()
int the cpp and
void DimmerCallback();
in the header.
A void* argument is a pointer that can point to any data type, it is not the same as void which is just no argument.
This question already has answers here:
Static Data Member Initialization
(7 answers)
Closed 7 years ago.
I am making a program for arduino. I am using avr-g+ 4.9.2 with STL from here.
I have a class Cocktail. I want all objects of type Cocktail to be able to access a vector of pointers. These pointers point to objects of type Alcohol. Seeing as this vector of pointers is the same for each instance of Cocktail, I wanted to make it static. But then my program fails to compile if I make them static. Here is the code:
Ineb.hpp
class Alcohol
{
private:
float flow_rate_;
Pump * which_pump_;
public:
std::string this_alcohol_;
Alcohol(std::string this_alcohol, float flow_rate);
Alcohol(std::string this_alcohol, float flow_rate, Pump which_pump);
float HowLong(float percentage_of_drink, uint8_t drink_size); //How long in seconds the pump should be on
void ChangeByteToRegister(uint8_t& byte_to_register);
};
class Cocktail
{
private:
bool order_matter_;
uint8_t byte_to_register_;
static std::vector<Alcohol*> alcohol_directory_;
public:
static void test(Alcohol *ba) {alcohol_directory_.push_back(ba);} //STATIC KEYWORD HERE
Cocktail(bool ordr_matter);
std::vector<std::string> GetIngredients(const uint8_t& num_ingredients, PGM_P& string_table);
uint8_t GetByteToRegister();
void MakeDrink(const uint8_t& num_ingredients, PGM_P& string_table);
};
main.cpp
#include "src/Ineb.hpp"
#include "src/Pins.hpp"
#include "ingredients.h"
#include <pnew.cpp>
extern "C" void __cxa_pure_virtual() {
for(;;);
}
int main(void) {
init();
setup();
Ineb::Pump A(1,8);
Ineb::Alcohol Vodka("vodka", 2.5, A);
Ineb::Cocktail::test(&Vodka);
for(;;)
loop();
return 0; // not reached
}
undefined reference to `Ineb::Cocktail::alcohol_directory_'
I'm mainly confused why this compiles when I take away static. What is static doing under the hood??
static members of classes must be defined outside the class definition.
Having the line
std::vector<Alcohol*> Cocktail::alcohol_directory_;
in Cocktail.cpp will do it.
I'm getting this linker error. I know a way around it, but it's bugging me because another part of the project's linking fine and it's designed almost identically.
First, I have namespace LCD. Then I have two separate files, LCDText.h and LCDGraphic.h.
LCDText.h:
//[snip]
void TextDraw(Widget *w);
void TextBarDraw(Widget *w);
void TextHistogramDraw(Widget *w);
void TextIconDraw(Widget *w);
void TextBignumsDraw(Widget *w);
void TextGifDraw(Widget *w);
}; // End namespace
LCDGraphic.h:
//[snip]
void GraphicDraw(Widget *w);
void GraphicIconDraw(Widget *w);
void GraphicBarDraw(Widget *w);
void GraphicHistogramDraw(Widget *w);
void GraphicBignumsDraw(Widget *w);
void GraphicGifDraw(Widget *w);
}; // End namespace
And in WidgetBignums.h I have:
//[snip]
using namespace LCD;
extern void TextBignumsDraw(Widget *w);
extern void GraphicBignumsDraw(Widget *w);
template <class T>
WidgetBignums<T>::WidgetBignums(Generic<T> *v, std::string n, Json::Value *section,
int row, int col) : Widget(n, section, row, col,
WIDGET_TYPE_BIGNUMS | WIDGET_TYPE_RC | WIDGET_TYPE_SPECIAL) {
if( v->GetType() == LCD_TEXT )
Draw = TextBignumsDraw; // Line 66
else if( v->GetType() == LCD_GRAPHIC )
Draw = GraphicBignumsDraw;
else
Draw = NULL;
//[snip]
And I get the following linker error:
LCDControl.o: In function `WidgetBignums':
/home/starlon/Projects/LCDControl/WidgetBignums.h:66: undefined reference to `LCD::TextBignumsDraw(LCD::Widget*)'
Now here's one way to fix it, but I don't like it. I can move LCD::TextBignumsDraw outside of the LCD namespace and it works. Strange enough, the linker sees LCD::GraphicBignumsDraw. Any clues?
Edit: I'm using gcc 4.4.1-2 on Fedora 11. Using SCons to compile.
Edit: Here's WidgetBignums, showing Draw.
template <class T>
class WidgetBignums : public Widget {
Generic<T> *visitor_;
std::vector<char> FB_;
std::vector<char> ch_;
int min_;
int max_;
int update_;
int layer_;
Property *expression_;
Property *expr_min_;
Property *expr_max_;
QTimer *timer_;
void (*Draw)(Widget *);
public:
WidgetBignums(Generic<T> *visitor, std::string name, Json::Value *section, int row, int col);
~WidgetBignums();
void TextScroll() {};
void SetupChars();
void Update();
void Start();
void Stop();
std::vector<char> GetFB() { return FB_; }
std::vector<char> GetCh() { return ch_; }
Generic<T> *GetVisitor() { return visitor_; }
};
Edit: Here's TextBignumsDraw's signature.
//[snip]
void TextBignumsDraw(Widget *w) {
//[snip]
Edit: Incidentally, I'm getting the same error for TextHistogramDraw and TextGifDraw as well. TextIconDraw and the others are fine.
Where is the definition for LCD::TextBignumsDraw()? That's what the linker seems to be complaining about. Not the declaration, but the actual definition of the function.
The fact that when you move the declaration out of namespace LCD things start working indicates that the definition for TextBignumsDraw() is in the global namespace, not the LCD namespace.
This (in some .cpp file):
void TextBignumsDraw(Widget *w) {
// ...
}
Needs to be wrapped in a
namespace LCD {
}
block.
Try dropping the "using namespace LCD", and change that line 66 to:
Draw = LCD::TextBignumsDraw;
That's more explicit, which may help the linker understand what you're asking for.
Besides, you should never say "using namespace Anything" in a header file. It hoists everything in that namespace out into the global space for every user of that header. That almost completely destroys the value of having a namespace in the first place. You should hoist things out like this in the narrowest scope that's practical. Sometimes I put "using namespace foo" at the top of a single function, for instance, if that's the only user of the bits in the namespace within a given .cpp file.