Why does this compile in C but not C++ (sigaction)? - c++

I get the following errors when trying to compile the below code using g++. When I compile it using gcc it works fine (other than a few warnings). Any help appreciated.
g++ ush7.cpp
ush7.cpp: In function ‘int signalsetup(sigaction*, sigset_t*, void (*)(int))’:
ush7.cpp:93: error: expected unqualified-id before ‘catch’
ush7.cpp:95: error: expected primary-expression before ‘catch’
ush7.cpp:95: error: expected `;' before ‘catch’
ush7.cpp:97: error: expected primary-expression before ‘catch’
ush7.cpp:97: error: expected `;' before ‘catch’
ush7.cpp:100: error: expected primary-expression before ‘catch’
ush7.cpp:100: error: expected `)' before ‘catch’
ush7.cpp:108: error: expected `)' before ‘;’ token
ush7.cpp:108: error: expected `)' before ‘;’ token
ush7.cpp: In function ‘int makeargv(const char*, const char*, char***)’:
ush7.cpp:137: error: invalid conversion from ‘void*’ to ‘char*’
ush7.cpp:145: error: invalid conversion from ‘void*’ to ‘char**’
int signalsetup(struct sigaction *def, sigset_t *mask, void (*handler)(int))
{
struct sigaction catch;
catch.sa_handler = handler; /* Set up signal structures */
def->sa_handler = SIG_DFL;
catch.sa_flags = 0;
def->sa_flags = 0;
if ((sigemptyset(&(def->sa_mask)) == -1) ||
(sigemptyset(&(catch.sa_mask)) == -1) ||
(sigaddset(&(catch.sa_mask), SIGINT) == -1) ||
(sigaddset(&(catch.sa_mask), SIGQUIT) == -1) ||
(sigaction(SIGINT, &catch, NULL) == -1) ||
(sigaction(SIGQUIT, &catch, NULL) == -1) ||
(sigemptyset(mask) == -1) ||
(sigaddset(mask, SIGINT) == -1) ||
(sigaddset(mask, SIGQUIT) == -1))
return -1;
return 0;
}

catch is a keyword in C++ but not in C.
Please see my related answer C is not a proper subset of C++ here, or even better here.

You should be able to use a #define if you don't want to change the rest of the code.
#define catch _catch

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.

‘graphresult’ was not declared in this scope

I'm trying to run a graphics program on my Ubuntu 18.04 LTS system to print the error code for failed graphics operation. My code is
#include <graphics.h>
#include <stdlib.h>
int main()
{
int gd, gm, errorcode;
initgraph(&gd, &gm, NULL);
errorcode = graphresult();
if(errorcode != grOk)
{
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to exit.");
getch();
exit(1);
}
getch();
closegraph();
return 0;
}
But when I run it I get the following error :
g++ -o mygraphics mygraphics.c -lgraph
mygraphics.c: In function ‘int main()’:
mygraphics.c:10:20: error: ‘graphresult’ was not declared in this scope
errorcode = graphresult();
^~~~~~~~~~~
mygraphics.c:12:24: error: ‘grOk’ was not declared in this scope
if(errorcode != grOk)
^~~~
mygraphics.c:12:24: note: suggested alternative: ‘brk’
if(errorcode != grOk)
^~~~
brk
mygraphics.c:14:42: error: ‘grapherrormsg’ was not declared in this scope
printf("Graphics error: %s\n", grapherrormsg(errorcode));
I searched all over the internet but not able to find a promising solution. Can someone help me out please. Thank you in advance :)

File.cpp:148: error: expected primary-expression before ‘.’ token DIFFERENT SYMBOL

I'm struggling to finish this code.
#include (sorry but it won't show up the #include such as stdio.h AND OTHERS) But this is not the problem.
using namespace std;
struct CustomerFile {
int arrivalTime;
string driverfName,
driverlName,
typeOfDriver,
driverLicNumber,
vehicleMake,
vehicleModel,
Lot_taken,
vehicleRegNumber,
attendantName,
ParkingArea,
Comments,
checkOutDateTime,
checkInDateTime;
};
int arrivalTime;
string driverfName,
driverlName,
typeOfDriver,
driverLicNumber,
vehicleMake,
vehicleModel,
Lot_taken,
vehicleRegNumber,
attendantName,
ParkingArea,
Comments,
checkOutDateTime,
checkInDateTime;
int main(int argc, char * * argv) {
FILE * cfPtr;
if ((cfPtr = fopen("CustomerFile.dat", "rb+")) == NULL) {
printf("file could not be opened");
} else {
printf("\nFile is Written to");
printf("\nFile is open");
printf("\n\n\nEnter Vehicle Registration Number: ");
scanf("%s", & CustomerFile.vehicleRegNumber);
while (CustomerFile.vehicleRegNumber != 0) /*#IF THE USER does not enter 0 the loops should begin, but there is a problem here*/
{
printf("\nFirst Name: ");
fscanf("%s", CustomerFile.driverfName); /*here is the problem, I think is had something to do with the struct name*/
printf("\nLast Name: ");
printf("\nType of Driver: ");
printf("\nDriver's License Number: ");
printf("\nVehicle Make: ");
printf("\nVehicle Model: ");
printf("\nComments ");
printf("\nParking SpaceTaken ");
printf("\n\nenter firstname, lastname");
fscanf(stdin, "%s%s%s%s%s%s%s%s1f", CustomerFile.driverfName I think this has something to do with the statement * /
CustomerFile.driverlName / * okay here * /
CustomerFile.typeOfDriver / * okay here * /
CustomerFile.driverLicNumber / * okay here * /
CustomerFile.vehicleMake / * okay here * /
CustomerFile.vehicleModel / * okay here * /
CustomerFile.Comments / * okay here * /
&CustomerFile.Lot_taken); / * okay here * /
fwrite( sizeof(struct CustomerFile ), 1, cfPtr);
}
fclose( cfPtr);
}
return 0;
}
Okay the problem is that it keeps giving the errors;*
File.cpp:144: error: expected primary-expression before ‘.’ token
File.cpp:148: error: expected primary-expression before ‘.’ token
File.cpp:162: error: expected primary-expression before ‘.’ token
File.cpp:172: error: invalid conversion from ‘unsigned int’ to ‘const void*’
File.cpp:172: error: invalid conversion from ‘FILE*’ to ‘size_t’
/usr/include/stdio.h:708: error: too few arguments to function ‘size_t fwrite(const void*, size_t, size_t, FILE*)’
File.cpp:172: error: at this point in file
I believed or read that it has something with the fact that a C++ complier does not work with c99. If so, then how do you use structs in c++? I know you use a struct by just for example CustomerFile.driverlName, however, the complier keep refusing it. Also I'm having problems with the while loop. I'm familiar with c and c++ we were taught both c and c++, the code is to be written in c++ but the text book gives c code that won't run in a c++ complier.
CustomerFile is a class, so it won't work when you try to access data members off of it as if it were an instance. To create an instance, do:
CustomerFile file;
And replace all instances of Customer. with file. and it should resolve the error.
You defined a datatype CustomerFile. For using defined structure CustomerFile you have create an object and use it. For eg :
CustomerFile customer;
customer.vehicleModel = "ABC";
vehicleRegNumber is of type string not integer compare it with 0 like this
while (customer.vehicleRegNumber != "0" )
Add , between variable names
fscanf( stdin, "%s%s%s%s%s%s%s%s1f", customer.driverfName, customer.driverlName ,
The fscanf() function is a C function, it does not know about std::string (or classes). So you have use a temp c string like this
char temp[100];
printf("\nFirst Name: ");
fscanf(stdin, "%99s", temp );
customer.driverfName = temp;

C++ "expected primary-expression before ‘(’ token" error

I have this code:
FILE *f = fopen(intPath, "r");
Node *n;
if (f) {
try {
n = parse(f, intPath);
} catch (SyntaxError e) {
fclose(f); /***** line 536 *****/
throw LangException(
builtin_classes::exception_class::create_ImportError(
String::fromAscii(e.filename)->
append(String::fromAscii(":"))->
append(String::fromInt(e.line))->
append(String::fromAscii(":"))->
append(String::fromInt(e.col))->
append(String::fromAscii(": syntax error: "))->
append(String::fromAscii(e.message))
);
}
fclose(f);
return n->eval(scope);
} else {
throw LangException(
builtin_classes::exception_class::create_ImportError(
String::fromAscii("failed to open file for reading")
),
line,
col
);
}
And the compiler gives this error:
nodes.cpp:537:40: error: expected primary-expression before ‘(’ token
nodes.cpp:544:94: error: expected ‘)’ before ‘;’ token
I have no clue what it could be, especially since that code sample has another statement which does the same thing, and it doesn't cause an error.
throw LangException(
builtin_classes::exception_class::create_ImportError(
String::fromAscii(e.filename)->
append(String::fromAscii(":"))->
append(String::fromInt(e.line))->
append(String::fromAscii(":"))->
append(String::fromInt(e.col))->
append(String::fromAscii(": syntax error: "))->
append(String::fromAscii(e.message))
) // This closes the function call
; // You didn't close the throw here!
Your ( and your ) don't match in that large, first throw LangException block.
The compiler tells you what is wrong. The throw LangException( doesn't have a ).
Exactly what it says. You are missing a ‘)’ before ‘;’ token on that line.
LangException(...
is not closed.

problem with va_arg()

I want to wirte a function with variable arguments in this way:
static void configElement(U32 localFaultId,
char* name,
U32 report,
U32 localId,
U32 detectTime,
U32 ceaseTime,...)
{
U32 i = 0;
U32 tmpNo = 0;
va_list ap;
if (nofFaults >= MAX_NOF_LOCAL_FAULTS)
{
//something here
return;
}
else
{
faultList[nofFaults].ceaseTime = ceaseTime;
va_start(ap, ceaseTime);
tmpNo = va_arg(ap, U32);
while ((tmpNo!= END_MARK) && (i < MAX_NOF_DEPEND))
{
faultList[nofFaults].dependList[i++].faultNo = tmpNo;
}
faultList[nofFaults].dependList[i].faultNo = END_MARK;
/* Finish by increment nofFaults parameter */
va_end(ap);
nofFaults++;
}
}
However, I got the error msg when compiling this code:
fault_manager.cc:3344: error: expected primary-expression before ',' token
fault_manager.cc:3387: error: expected primary-expression before 'U32'
fault_manager.cc:3387: error: expected `)' before 'U32'
fault_manager.cc:3387: error: expected `)' before ';' token
fault_manager.cc:3387: error: expected `)' before ';' token
I have no idea what is going wrong here. My platform is Windows, and I'm using cygwin+Eclipse(CDT). The version of gcc is 4.1.1.
Any idea will be appreciated much!
It looks like the compiler does not know what U32 is. Did you include all necessary headers?