g++ was not declared in this scope - c++

I im writing sqlite3 wrapper with class to read db file. I im using ubuntu 64-bit and g++ compiler...and when i run code above i get this:
g++ ezserver.cpp -lsqlite3 -o ezserver
ezserver.cpp: In function int main():
ezserver.cpp:7:2: error: DataBase was not declared in this scope
DataBase = new EZServer();
^
database.h
#ifndef DATABASE_H
#define DATABASE_H
/* LIBRARY */
#include <sqlite3.h>
/* CLASS */
class EZServer {
public:
EZServer();
~EZServer();
int OpenDataBase(const char *TFileName);
int CreateDataBase(const char *TFileName);
private:
sqlite3 *DataBase;
sqlite3_stmt *QueryHandle[2];
};
#endif
database.cpp
#include "database.h"
/* CONSTRUCTOR */
EZServer::EZServer(): DataBase(0) {
QueryHandle[0] = NULL;
QueryHandle[1] = NULL;
}
/* DESTRUCTOR */
EZServer::~EZServer() {
/* CLOSE - database */
if (DataBase) {
sqlite3_close(DataBase);
}
}
/* LOAD - database file */
int EZServer::OpenDataBase(const char *TFileName) {
/* OPEN - database */
int Result = sqlite3_open_v2(TFileName, &DataBase, SQLITE_OPEN_READWRITE, NULL);
/* CHECK - database */
if (Result != SQLITE_OK) {
printf("OpenDataBase: %s\n", sqlite3_errmsg(DataBase));
sqlite3_close(DataBase);
return 0;
}
return 1;
}
/* CREATE - database file */
int EZServer::CreateDataBase(const char *TFileName) {
/* OPEN - database */
int Result = sqlite3_open_v2(TFileName, %DataBase, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
/* CHECK - database */
if (Result != SQLITE_OK) {
printf("OpenDataBaseCreate: %s\n", sqlite3_errmsg(DataBase));
sqlite3_close(DataBase);
return 0;
}
return 1;
}
ezserver.h
#ifndef EZSERVER_H
#define EZSERVER_H
/* FORWARD - declarations */
class EZServer;
/* CLASS */
class StatsClass {
public:
int Init();
private:
EZServer *DataBase;
};
#endif
ezserver.cpp
#include "ezserver.h"
#include "database.h"
int main() {
DataBase = new EZServer();
}
main file is ezserver.cpp.
i im beginner in c++ so i read posts here try solutions but always get DataBase was not declared in this scope...could some one give solution?
Thanks.
EDIT:
I need to call EZServer() class name that holds functions like OpenDataBase CreateDataBase.
// Load database that opens save and query
Database = new EZServer();
Database->OpenDatabase("ezserver.db");
so i need this above ->OpenDataBase to be called from EZServer.cpp (main file program) and return from class EZServer value that function is defined in database.cpp

I found another problem, you should compile all *.cpp files.
g++ ezserver.cpp database.cpp -lsqlite3 -o ezserver
here is log when i run this:
g++ ezserver.cpp database.cpp -lsqlite3 -o ezserver database.cpp:4:20:
error: definition of implicitly-declared ‘EZServer::EZServer()’
EZServer::EZServer(): DataBase(0) { ^ database.cpp:10:21: error:
definition of implicitly-declared ‘EZServer::~EZServer()’
EZServer::~EZServer() { ^ database.cpp: In member function ‘int
EZServer::OpenDataBase(const char*)’: database.cpp:20:76: error:
‘NULL’ was not declared in this scope int Result =
sqlite3_open_v2(TFileName, &DataBase, SQLITE_OPEN_READWRITE, NULL); ^
database.cpp:24:56: error: ‘printf’ was not declared in this scope
printf("OpenDataBase: %s\n", sqlite3_errmsg(DataBase)); ^
database.cpp: In member function ‘int EZServer::CreateDataBase(const
char*)’: database.cpp:34:42: error: expected primary-expression
before ‘%’ token int Result = sqlite3_open_v2(TFileName,
%DataBase, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL); ^
database.cpp:34:97: error: ‘NULL’ was not declared in this scope
int Result = sqlite3_open_v2(TFileName, %DataBase,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL); ^
database.cpp:38:62: error: ‘printf’ was not declared in this scope
printf("OpenDataBaseCreate: %s\n", sqlite3_errmsg(DataBase)); ^

Maybe you should write something like this:
EZServer* dataBase = new EZServer();
dataBase->OpenDataBase("ezserver.db");

Related

error: invalid conversion from ‘int’ to ‘void*’ [-fpermissive] in the given set of commands

I have c++ file like below one,
#include <iostream>
using namespace std;
extern "C" {
#include "sample_publish.c"
}
int main()
{
int antenna_id = 123;
send_message_to_mqtt(&antenna_id);
}
I have included a c file in c++ file and I need to pass the variable antenna_id to the function send_message_to_mqtt and the same is in c file like below one.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
void send_message_to_mqtt(int *antenna_id) {
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
int rc;
MQTTClient_create(&client, "tcp://mqtt1.mindlogic.com:1883", "ExampleClientPub",
MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
printf("DATA FROM C++:::%d\n", *antenna_id);
char payload_data[] = "hi";
//pubmsg.payload = payload_data;
pubmsg.payload = *antenna_id
pubmsg.payloadlen = (int)strlen(*antenna_id);
pubmsg.qos = 1;
pubmsg.retained = 0;
MQTTClient_publishMessage(client, "MQTT-Examples", &pubmsg, &token);
printf("Waiting for up to %d seconds for publication of %s\n""on topic %s for client with ClientID: %s\n",(int)(10000L/1000), "Hello World!", "MQTT-Examples", "ExampleClientPub");
rc = MQTTClient_waitForCompletion(client, token, 10000L);
printf("Message with delivery token %d delivered\n", token);
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
// return rc;
}
When I execute a c++ file, the antenna_id variable is doesnt accessible in c file which in turn not allowing me to map against pubmsg.payload and this is due to the below error,
dell#dell-Inspiron-5379:~/workspace_folder$ g++ sample.cpp -o sample -lpaho-mqtt3c
In file included from sample.cpp:5:0:
sample_publish.c: In function ‘void send_message_to_mqtt(int*)’:
sample_publish.c:30:22: error: invalid conversion from ‘int’ to ‘void*’ [-fpermissive]
pubmsg.payload = *antenna_id
^~~~~~~~~~~
sample_publish.c:31:5: error: expected ‘;’ before ‘pubmsg’
pubmsg.payloadlen = (int)strlen(*antenna_id);
^~~~~~
How to overcome this one?
A guess on the problem, it's most likely this line:
pubmsg.payload = *antenna_id
Besides missing the semicolon, the payload is a pointer to the first byte of the data to be sent. That is, you should not dereference the pointer:
pubmsg.payload = antenna_id;
On a related note, this line is also very wrong:
pubmsg.payloadlen = (int)strlen(*antenna_id);
The strlen function is to get the length if a null-terminate byte string.
The length of an int can be gotten with the sizeof operator:
pubmsg.payloadlen = sizeof *antenna_id;
Note that here you must use the dereference operator, otherwise you get the size of the pointer itself.

cec code not working with libcec 4

I am running stretch on raspberry pi 1. Only libcec4 and libcec4-dev are available in repo.
Simple code I found from github is based on old version of libcec.
// Build command:
// g++-4.8 -std=gnu++0x -fPIC -g -Wall -march=armv6 -mfpu=vfp -mfloat-abi=hard -isystem /opt/vc/include/ -isystem /opt/vc/include/interface/vcos/pthreads/ -isystem /opt/vc/include/interface/vmcs_host/linux/ -I/usr/local/include -L /opt/vc/lib -lcec -lbcm_host -ldl cec-simplest.cpp -o cec-simplest
//#CXXFLAGS=-I/usr/local/include
//#LINKFLAGS=-lcec -ldl
#include <libcec/cec.h>
// cecloader.h uses std::cout _without_ including iosfwd or iostream
// Furthermore is uses cout and not std::cout
#include <iostream>
using std::cout;
using std::endl;
#include <libcec/cecloader.h>
#include "bcm_host.h"
//#LINKFLAGS=-lbcm_host
#include <algorithm> // for std::min
// The main loop will just continue until a ctrl-C is received
#include <signal.h>
bool exit_now = false;
void handle_signal(int signal)
{
exit_now = true;
}
//CEC::CBCecKeyPressType
int on_keypress(void* not_used, const CEC::cec_keypress msg)
{
std::string key;
switch( msg.keycode )
{
case CEC::CEC_USER_CONTROL_CODE_SELECT: { key = "select"; break; }
case CEC::CEC_USER_CONTROL_CODE_UP: { key = "up"; break; }
case CEC::CEC_USER_CONTROL_CODE_DOWN: { key = "down"; break; }
case CEC::CEC_USER_CONTROL_CODE_LEFT: { key = "left"; break; }
case CEC::CEC_USER_CONTROL_CODE_RIGHT: { key = "right"; break; }
default: break;
};
std::cout << "on_keypress: " << static_cast<int>(msg.keycode) << " " << key << std::endl;
return 0;
}
int main(int argc, char* argv[])
{
// Install the ctrl-C signal handler
if( SIG_ERR == signal(SIGINT, handle_signal) )
{
std::cerr << "Failed to install the SIGINT signal handler\n";
return 1;
}
// Initialise the graphics pipeline for the raspberry pi. Yes, this is necessary.
bcm_host_init();
// Set up the CEC config and specify the keypress callback function
CEC::ICECCallbacks cec_callbacks;
CEC::libcec_configuration cec_config;
cec_config.Clear();
cec_callbacks.Clear();
const std::string devicename("CECExample");
devicename.copy(cec_config.strDeviceName, std::min(devicename.size(),13u) );
cec_config.clientVersion = CEC::LIBCEC_VERSION_CURRENT;
cec_config.bActivateSource = 0;
cec_config.callbacks = &cec_callbacks;
cec_config.deviceTypes.Add(CEC::CEC_DEVICE_TYPE_RECORDING_DEVICE);
cec_callbacks.CBCecKeyPress = &on_keypress;
// Get a cec adapter by initialising the cec library
CEC::ICECAdapter* cec_adapter = LibCecInitialise(&cec_config);
if( !cec_adapter )
{
std::cerr << "Failed loading libcec.so\n";
return 1;
}
// Try to automatically determine the CEC devices
CEC::cec_adapter devices[10];
int8_t devices_found = cec_adapter->FindAdapters(devices, 10, NULL);
if( devices_found <= 0)
{
std::cerr << "Could not automatically determine the cec adapter devices\n";
UnloadLibCec(cec_adapter);
return 1;
}
// Open a connection to the zeroth CEC device
if( !cec_adapter->Open(devices[0].comm) )
{
std::cerr << "Failed to open the CEC device on port " << devices[0].comm << std::endl;
UnloadLibCec(cec_adapter);
return 1;
}
// Loop until ctrl-C occurs
while( !exit_now )
{
// nothing to do. All happens in the CEC callback on another thread
sleep(1);
}
// Close down and cleanup
cec_adapter->Close();
UnloadLibCec(cec_adapter);
return 0;
}
It does not compile using libcec4 and libcec4-dev and throws these errors ::
cec-simplest.cpp: In function ‘int main(int, char**)’:
cec-simplest.cpp:76:19: error: ‘CEC::ICECCallbacks {aka struct CEC::ICECCallbacks}’ has no member named ‘CBCecKeyPress’; did you mean ‘keyPress’?
cec_callbacks.CBCecKeyPress = &on_keypress;
^~~~~~~~~~~~~
cec-simplest.cpp:88:41: error: ‘class CEC::ICECAdapter’ has no member named ‘FindAdapters’; did you mean ‘PingAdapter’?
int8_t devices_found = cec_adapter->FindAdapters(devices, 10, NULL);
When I renamed CBCecKeyPress to keyPress and FindAdapters to PingAdapter , I got these errors ::
cec-simplest.cpp: In function ‘int main(int, char**)’:
cec-simplest.cpp:76:33: error: invalid conversion from ‘int (*)(void*, CEC::cec_keypress)’ to ‘void (*)(void*, const cec_keypress*) {aka void (*)(void*, const CEC::cec_keypress*)}’ [-fpermissive]
cec_callbacks.keyPress = &on_keypress;
^~~~~~~~~~~~
cec-simplest.cpp:88:70: error: no matching function for call to ‘CEC::ICECAdapter::PingAdapter(CEC::cec_adapter [10], int, NULL)’
int8_t devices_found = cec_adapter->PingAdapter(devices, 10, NULL);
^
In file included from cec-simplest.cpp:5:0:
/usr/include/libcec/cec.h:77:18: note: candidate: virtual bool CEC::ICECAdapter::PingAdapter()
virtual bool PingAdapter(void) = 0;
^~~~~~~~~~~
/usr/include/libcec/cec.h:77:18: note: candidate expects 0 arguments, 3 provided
Some Info that I got about keyPress from /usr/include/libcec/cectypes.h ::
typedef struct cec_keypress
{
cec_user_control_code keycode; /**< the keycode */
unsigned int duration; /**< the duration of the keypress */
} cec_keypress;
typedef struct ICECCallbacks
{
void (CEC_CDECL* keyPress)(void* cbparam, const cec_keypress* key);
/*!
* #brief Transfer a CEC command from libCEC to the client.
* #param cbparam Callback parameter provided when the callbacks were set up
* #param command The command to transfer.
*/
void Clear(void)
{
keyPress = nullptr;
There is no documentation available for libcec.
What modifications do I need to do to make it work with libcec4 ?
I'm the author of the code you are asking about. I know that a year has passed since you asked the question but I only stumbled onto this stackoverflow question because I was searching for the solution myself! LOL. Luckily I've cracked the problem by myself.
I've updated the github code to work https://github.com/DrGeoff/cec_simplest and I've written a blog post about the code https://drgeoffathome.wordpress.com/2018/10/07/a-simple-libcec4-example-for-the-raspberry-pi/
In short, these are the changes I had to make. First up, the on_keypress function now is passed a pointer to a cec_keypress message rather than a by-value copy of a message. The next change is that the CEC framework has changed the name of the callback function from CBCecKeyPress to the simple keyPress. In a similar vein, the FindAdapters function is now DetectAdapters (not PingAdapters as you tried). And finally, the DetectAdapters function fills in an array of cec_adapter_descriptor rather than cec_adapter, which has the flow on effect to the Open call taking a strComName rather than simply comm.

How to get C/C++ module information with libclang

I am trying to use the module functionalities from libclang. Here is the context:
I have a clang module defined and a source file that call it:
module.modulemap
module test {
requires cplusplus
header "test.h"
}
test.h :
#pragma once
static inline int foo() { return 1; }
test.cpp :
// Try the following command:
// clang++ -fmodules -fcxx-modules -fmodules-cache-path=./cache_path -c test.cpp
// If you see stuff in the ./cache_path directory, then it works!
#include "test.h"
int main(int, char **) {
return foo();
}
cache_path is at first empty then after the command I can see stuff in it so this is working.
My problem is when I try to use libclang to parse the test.cpp file in order to get informations about module:
#include <stdio.h>
#include "clang-c/Index.h"
/*
compile with:
clang -lclang -o module_parser module_parser.c
*/
static enum CXChildVisitResult
visitor(CXCursor cursor, CXCursor parent, CXClientData data)
{
CXSourceLocation loc;
CXFile file;
CXString module_import;
CXModule module;
CXString module_name;
CXString module_full_name;
unsigned line;
unsigned column;
unsigned offset;
if (clang_getCursorKind(cursor) == CXCursor_ModuleImportDecl)
{
loc = clang_getCursorLocation(cursor);
clang_getSpellingLocation(loc,
&file,
&line,
&column,
&offset);
module_import = clang_getCursorSpelling(cursor);
printf("Module import dec at line: %d \"%s\"\n", line, clang_getCString(module_import));
clang_disposeString(module_import);
}
module = clang_Cursor_getModule(cursor);
module_name = clang_Module_getName(module);
module_full_name = clang_Module_getFullName(module);
printf("Module name %s , full name %s\n", clang_getCString(module_name),
clang_getCString(module_full_name));
clang_disposeString(module_name);
clang_disposeString(module_full_name);
return CXChildVisit_Recurse; // visit complete AST recursivly
}
int main(int argc, char *argv[]) {
CXIndex Index = clang_createIndex(0, 1);
const char *args[] = { "-x",
"c++",
"-fmodules",
"-fcxxmodules"//,
"-fmodules-cache-path",
"cache_path"
};
CXTranslationUnit TU = clang_createTranslationUnitFromSourceFile(Index,
"test.cpp",
6,
args,
0,
0);
clang_visitChildren(clang_getTranslationUnitCursor(TU), visitor, 0);
clang_disposeTranslationUnit(TU);
clang_disposeIndex(Index);
return 0;
}
The output of this code is :
...
Module name , full name
Module name , full name
Module name , full name
Module name , full name
Module name , full name
...
First it seems that clang doesn't detect any cursor of the kind CXCursor_ModuleImportDecl and then at any momment it find a valid module.
What am I doing wrong?

Calling Lua function from string_t

I have some functions declared and initialized in .lua file. Then, when I receive signal, I read string_t variable with the name of function to call from file. The problem is that I don't know how to push function to stack by its name or call it.
For example:
test.lua
function iLoveVodka()
--some text
end
function iLoveFish()
--another text
end
C File:
string_t a = "iLoveVodka()"
How can i call function from C/C++ code iLoveVodka() only by having its name?
Here is some sample code that does two things:
Loads the file "test.lua" from the same directory.
Tries to call the function iLoveVodka(), if it can be found.
You should be able to build this easily enough:
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[])
{
lua_State *l = luaL_newstate ();
luaL_openlibs (l);
int error = luaL_dofile (l, "test.lua");
if (error)
{
printf( "Error loading test.lua: %s\n",luaL_checkstring (l, -1) );
exit(1);
}
/**
* Get the function and call it
*/
lua_getglobal(l, "iLoveVodka");
if ( lua_isnil(l,-1) )
{
printf("Failed to find global function iLoveVodka\n" );
exit(1);
}
lua_pcall(l,0,0,0);
/**
* Cleanup.
*/
lua_close (l);
return 0;
}
This can be compiled like this:
gcc -O -o test `pkg-config --libs --cflags lua5.1` test.c
Just define your iLoveVodka() function inside test.lua, and you should be OK.

Extending Python 3 with C++

I'm trying to extend Python 3 using instructions given here and I'm fairly confident I've followed the instructions correctly so far, but it asks me to include this code:
PyMODINIT_FUNC
PyInit_spam(void)
{
PyObject *m;
m = PyModule_Create(&spammodule);
if (m == NULL)
return NULL;
SpamError = PyErr_NewException("spam.error", NULL, NULL);
Py_INCREF(SpamError);
PyModule_AddObject(m, "error", SpamError);
return m;
}
I'm writing this in MSVC++ 2010 and it's warning me that &spammodule is undefined (the name of the module is spammodule.cpp), but it doesn't define it anywhere in the instructions so I assume that it should recognise it automatically as the name of the module.
The full code is:
#include <Python.h>
#include <iostream>
using namespace std;
static PyObject *SpamError;
int main()
{
cout << "Test" << endl;
system("PAUSE");
return(0);
}
static PyObject *spam_system(PyObject *self, PyObject *args)
{
const char *command;
int sts;
if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = system(command);
return PyLong_FromLong(sts);
}
PyMODINIT_FUNC
PyInit_spam(void)
{
PyObject *m;
m = PyModule_Create(&spammodule);
if (m == NULL)
return NULL;
SpamError = PyErr_NewException("spam.error", NULL, NULL);
Py_INCREF(SpamError);
PyModule_AddObject(m, "error", SpamError);
return m;
}
You're still writing C++, so you still need to declare spammodule somewhere. This is given later on the same page:
static struct PyModuleDef spammodule = {
PyModuleDef_HEAD_INIT,
"spam", /* name of module */
spam_doc, /* module documentation, may be NULL */
-1, /* size of per-interpreter state of the module,
or -1 if the module keeps state in global variables. */
SpamMethods
};
No no no, PyModule_Create() accepts a pointer to the module definition structure and has absolutely nothing to do with the name of the source file.