I am getting an error on a specific line that mimics the usage in another file.
PyObject *pyCharGetHeight(PyChar *self, void *closure) {
CHAR_DATA *ch = PyChar_AsChar((PyObject *)self);
PyObject *height = NULL;
if(ch != NULL) height = Py_BuildValue("s", charGetHeight(ch));
return height;
}
PyChar_addGetSetter("height", pyCharGetHeight, NULL, "Returns character's height");
is returning the following error, PyChar_addGetSetter… line
error: expected declaration specifiers or â…â before string constant
I am using the following includes:
#include <Python.h>
#include "../scripts/pychar.h"
And pychar.h does define PyChar_addGetSetter() as prototyped here:
void PyChar_addGetSetter(const char *name, void *g, void *s, const char *doc);
The function is written in ../scripts/pychar.c as follows:
void PyChar_addGetSetter(const char *name, void *g, void *s, const char *doc) {
// make sure our list of get/setters is created
if(pychar_getsetters == NULL) pychar_getsetters = newList();
// make the GetSetter def
PyGetSetDef *def = calloc(1, sizeof(PyGetSetDef));
def->name = strdup(name);
def->get = (getter)g;
def->set = (setter)s;
def->doc = (doc ? strdup(doc) : NULL);
def->closure = NULL;
listPut(pychar_getsetters, def);
}
It seems like a structure or type is not being recognized, I am guessing my function.
I had the same problem. My error messages were:
TarHeader.h:15:24: error: expected declaration specifiers or '...' before numeric constant TarHeader.c:69:61: error: expected declaration specifiers or '...' before string constant
And the specific lines of code were:
* Line 15 in TarHeader.h:
#define TAR_BLOCK_SIZE 512
* Line 69 (v1) in TarHeader.c:
static_assert(TAR_BLOCK_SIZE == sizeof(tar_posix_header_t), "Incorrect header definition");
When I tried to change it I changed the includes in «TarHeader.c» (removed include of «TarHeader.h»)
The line seems then like this (Line 69 (v2) in TarHeader.c)
static_assert(512== sizeof(tar_posix_header_t), "Incorrect header definition");
And the error codes changed:
TarHeader.c:69:15: error: expected declaration specifiers or '...' before numeric constant TarHeader.c:69:50: error: expected declaration specifiers or '...' before string constant
When I removed line 65 of «TarHeader.c» no error was reported even with the previously used include.
The static assert was copied from another project (also in C) ane there was no problem. But it was a different compiler.
Solution:
Search for the use of these defines and see what use causes this problem.
You can not use a function call (printf
) outside a function. You should take a look at #error
if you want to report errors at compilation…
See here
Related videos on Youtube
05 : 58
Understanding errors and how to fix them
02 : 54
Error: requires a type specifier for all declarations, return type of out of line definition of
Legendary Computer Programmer
01 : 52
[ERROR] EXPECTED ‘;’ BEFORE… || C LANGUAGE || ERROR IN PROGRAMMING || DEV C++
04 : 09
[Error] #include expects «FILENAME»|[Error]expected declaration specifiers| SaiBalajiEducationहिन्दी
02 : 06
expect ‘}’ at end of input e expected declaration before ‘}’ token no arduino
01 : 00
expected declaration or statement at end of input
05 : 00
[Error] expected ‘}’ before ‘;’ token || ‘;’ before ‘}’ token || hindi || SaiBalajiEducationहिन्दी
02 : 00
Expected ‘;’ before ‘}’ token no arduino
00 : 29
C | Bug Hunting Error Expected Declaration or Statement at End of Input
Comments
-
Does anybody know what is wrong with this piece of code? i can’t see to find the issue among the comparable questions.
The code is written in C, and i keep getting this error. I do add
-D SET_MIN_TEMP=5 -D Set_MAX_TEMP=30
to the gcc compile line to make sure the ifndefs should be false…#ifndef CONFIG_H #define CONFIG_H #include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdint.h> #ifndef RUN_AVG_LENGTH #define RUN_AVG_LENGTH 5 #endif #ifndef SET_MIN_TEMP printf("please set SET_MIN_TEMP n"); #endif #ifndef SET_MAX_TEMP printf("please set SET_MAX_TEMP n"); #endif typedef uint16_t sensor_id_t; typedef uint16_t room_id_t; typedef double sensor_value_t; typedef time_t sensor_ts_t; // UTC timestamp as returned by time() - notice that the size of time_t is different on 32/64 bit machine typedef struct { sensor_id_t id; sensor_value_t value; sensor_ts_t ts; } sensor_data_t; typedef struct { sensor_id_t sensor_id; room_id_t room_id; double running_avg[5]; sensor_ts_t timestamp; } sensor_node_t; #endif // CONFIG_H
-
Set_MAX_TEMP
!=SET_MAX_TEMP
because C is case-sensitive. -
Which line are you getting an error for? Why do you have
printf()
lines at top-level like this? -
If you want to cause compile-time errors when a macro isn’t defined use
#error
.
-
-
The
#ifndef
is supposed to hide those calls and prevent the error. -
Yes, but it seems like that the OP passed the wrong arguments (case), so the wrong
printf
statements will remain… -
I think that’s the point — he was really wondering why the
#ifndef
wasn’t working. And it turned out to be a simple typo. -
I also think that, but nevertheless the
printf
is wrong and should be replaced… -
I agree with that, which is why I wrote it in a comment 15 minutes ago.
Recents
Related
After compiling my program of Dice Roll, I got this error. What is wrong with the code?
Also before I was using gets() instead of scanf() command, but because of that I got this error — passing argument 1 of ‘gets’ makes pointer from integer without a cast
So I removed the gets() command and used scanf and then there was no error regarding scanf().
What is the reason for getting these two errors?
Ok, so as per the answer I got to know how I should have used the gets() command and why I shouldn’t use it instead should use scanf(). So, I made the changes.
Though I have encountered two new errors, this time it’s related to the delay() command that I used.
Errors: undefined reference to delay
|error: ld returned 1 exit status|
OK so I solved my last errors by using Sleep() command from windows.h library instead of Delay() command. The programs was compiled.
But still there is a runtime error in the program, it works well till getting the roll1 but then it just print the next two statement and terminated the programs without taking a input for the guess.
It skips all the code after printf("Will it be Higher/Lower or the same? (press H/L/S)n");
and directly terminates the program.
Ok So I solved above problem adding a whitespace before the "%c"
in scanf(" %c", &nextGuess);
statement. (Little things xD)
Now only problem is that my toupper()
command is not working.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <windows.h>
int main()
{
int i, roll1=0, roll2=0, NumberOfRolls, RandomNUM1[50], RandomNUM2[50];
char nextGuess;
puts("Welcome to the Dice Roll Game");
puts("How many times do you want to roll a dice?");
scanf("%d", &NumberOfRolls);
for( i=1; i<=NumberOfRolls; i++ ) {
RandomNUM1[i] = ( rand()%6 ) + 1;
roll1 += RandomNUM1[i];
}
printf("nYou Got %d in your first roll!n", roll1);
Sleep(3000);
printf("nLet's see if you can guess the value of next roll.n");
printf("Will it be Higher/Lower or the same? (press H/L/S)n");
scanf(" %c", &nextGuess);
toupper(nextGuess);
for( i=1; i<=NumberOfRolls; i++ ) {
RandomNUM2[i] = ( rand()%6 ) + 1;
roll2 += RandomNUM2[i];
}
if(nextGuess=='H'){
if(roll1<roll2){
printf("You are such a player, you guessed it right! It's %d", roll2);
}
else if(roll1>roll2){
printf("Uh-Oh! Bad Luck! First roll was higher, It's %d", roll2);
}
else if(roll1==roll2){
printf("Uh-Oh! Bad Luck! Both the rolls are same, It's %d", roll2);
}
}
if(nextGuess=='L'){
if(roll1>roll2){
printf("You are such a player, you guessed it right! It's %d", roll2);
}
else if(roll1<roll2){
printf("Uh-Oh! Bad Luck! First roll was lower, It's %d", roll2);
}
else if(roll1==roll2){
printf("Uh-Oh! Bad Luck! Both the rolls are same, It's %d", roll2);
}
}
if(nextGuess=='S'){
if(roll1==roll2){
printf("You are such a player, you guessed it right! It's %d", roll2);
}
else if(roll1>roll2){
printf("Uh-Oh! Bad Luck! First roll was higher, It's %d", roll2);
}
else if(roll1<roll2){
printf("Uh-Oh! Bad Luck! Second roll is higher, It's %d", roll2);
}
}
return 0;
}
I had the same problem. My error messages were:
TarHeader.h:15:24: error: expected declaration specifiers or '...' before numeric constant TarHeader.c:69:61: error: expected declaration specifiers or '...' before string constant
And the specific lines of code were:
* Line 15 in TarHeader.h:
#define TAR_BLOCK_SIZE 512
* Line 69 (v1) in TarHeader.c:
static_assert(TAR_BLOCK_SIZE == sizeof(tar_posix_header_t), "Incorrect header definition");
When I tried to change it I changed the includes in «TarHeader.c» (removed include of «TarHeader.h»)
The line seems then like this (Line 69 (v2) in TarHeader.c)
static_assert(512== sizeof(tar_posix_header_t), "Incorrect header definition");
And the error codes changed:
TarHeader.c:69:15: error: expected declaration specifiers or '...' before numeric constant TarHeader.c:69:50: error: expected declaration specifiers or '...' before string constant
When I removed line 65 of «TarHeader.c» no error was reported even with the previously used include.
The static assert was copied from another project (also in C) ane there was no problem. But it was a different compiler.
Solution:
Search for the use of these defines and see what use causes this problem.
0
0
Добрый день!
При компиляции libpcap возникла непонятная ошибка:
gcc -nodefaultlibs -nostdlib -fPIC -static -I/home/xvilka/build/cross/sys-root/usr/include -O2
-fPIC -nodefaultlibs -nostdlib -fPIC -static -I/home/xvilka/build/cross/sys-root/usr/include -I.
-DHAVE_CONFIG_H -D_U_="__attribute__((unused))" -c ./pcap-usb-linux.c
In file included from ./pcap-usb-linux.c:57:
/home/xvilka/build/cross/sys-root/usr/include/string.h:431: error: expected declaration specifiers or '...' before '(' token
/home/xvilka/build/cross/sys-root/usr/include/string.h:431: error: expected declaration specifiers or '...' before '(' token
/home/xvilka/build/cross/sys-root/usr/include/string.h:431: error: expected declaration specifiers or '...' before '(' token
/home/xvilka/build/cross/sys-root/usr/include/string.h:431: error: expected ')' before ',' token
make[1]: *** [pcap-usb-linux.o] Error 1
В чем может быть проблема? (такую ошибку в первый раз встречаю)
Некоторые флаги компилятора повторяются, хотя при .configure были заданы один раз, но уверен это не играет здесь роли.
Помогите с решением, спасибо!
Ожидаемые спецификаторы объявления или ‘…’ перед строковой константой
я осознаю Expected declaration specifiers or '...' before string constant
ошибка в mach_override.c in проект scplugin во второй строке кода ниже.
asm(
".text;"
".align 2, 0x90;"
".globl _atomic_mov64;"
"_atomic_mov64:;"
" pushl %ebp;"
" movl %esp, %ebp;"
" pushl %esi;"
" pushl %ebx;"
" pushl %ecx;"
" pushl %eax;"
" pushl %edx;"
// atomic push of value to an address
// we use cmpxchg8b, which compares content of an address with
// edx:eax. If they are equal, it atomically puts 64bit value
// ecx:ebx in address.
// We thus put contents of address in edx:eax to force ecx:ebx
// in address
" mov 8(%ebp), %esi;" // esi contains target address
" mov 12(%ebp), %ebx;"
" mov 16(%ebp), %ecx;" // ecx:ebx now contains value to put in target address
" mov (%esi), %eax;"
" mov 4(%esi), %edx;" // edx:eax now contains value currently contained in target address
" lock; cmpxchg8b (%esi);" // atomic move.
// restore registers
" popl %edx;"
" popl %eax;"
" popl %ecx;"
" popl %ebx;"
" popl %esi;"
" popl %ebp;"
" ret"
);
Allow asm, inline typeof
Флаг установлен в моих настройках сборки. кто-нибудь может мне помочь?
Сделайте следующее изменение (во флагах):
C language dialect = Compiler Default
Создан 02 янв.
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
objective-c
xcode
gcc
inline-assembly
or задайте свой вопрос.
Forum rules
Before you post please read how to get help. Topics in this forum are automatically closed 6 months after creation.
-
hhbuur
- Level 1
- Posts: 12
- Joined: Thu Feb 15, 2018 1:17 pm
[SOLVED]Make error
Can I get some help with understand these error messages. I am trying to make a hello world.
#include<linux/init.h>
#include<linux/module.h>MODUL_LICENSE(«GPL»);
static int hello_init(void)
{
printk(KERN_ALERT «Hello world»);
retur 0;
}static void hello_exit(void)
{
printk(KERN_Alert «Goodby»);
}module_init(hello_init);
module_exit(hello_exit);obj-m +=hello.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
hhb # make
make -C /lib/modules/4.13.0-39-generic/build M=/home/hans/hhb modules
make[1]: Entering directory ‘/usr/src/linux-headers-4.13.0-39-generic’
CC [M] /home/hans/hhb/hello.o
/home/hans/hhb/hello.c:4:15: error: expected declaration specifiers or ‘…’ before string constant
MODUL_LICENSE(«GPL»);
^
/home/hans/hhb/hello.c: In function ‘hello_init’:
/home/hans/hhb/hello.c:9:1: error: ‘retur’ undeclared (first use in this function)
retur 0;
^
/home/hans/hhb/hello.c:9:1: note: each undeclared identifier is reported only once for each function it appears in
/home/hans/hhb/hello.c:9:7: error: expected ‘;’ before numeric constant
retur 0;
^
/home/hans/hhb/hello.c:10:1: warning: no return statement in function returning non-void [-Wreturn-type]
}
^
/home/hans/hhb/hello.c: In function ‘hello_exit’:
/home/hans/hhb/hello.c:14:8: error: ‘KERN_Alert’ undeclared (first use in this function)
printk(KERN_Alert «Goodby»);
^
/home/hans/hhb/hello.c:14:19: error: expected ‘)’ before string constant
printk(KERN_Alert «Goodby»);
^
scripts/Makefile.build:323: recipe for target ‘/home/hans/hhb/hello.o’ failed
make[2]: *** [/home/hans/hhb/hello.o] Error 1
Makefile:1550: recipe for target ‘_module_/home/hans/hhb’ failed
make[1]: *** [_module_/home/hans/hhb] Error 2
make[1]: Leaving directory ‘/usr/src/linux-headers-4.13.0-39-generic’
Makefile:4: recipe for target ‘all’ failed
make: *** [all] Error 2
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 2 times in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
Linux Mint XFce 19.3
Lenovo ThinkPad W530 /2010
-
rene
- Level 20
- Posts: 11266
- Joined: Sun Mar 27, 2016 6:58 pm
Re: Make error
Post
by rene » Sat Jul 28, 2018 4:49 pm
You have 3 obvious typo’s, all of which are pointed out by the error messages. Modulo module signing, the only thing that’s otherwise wrong is that you should end your printk strings with «n» so as to flush them to the kernel message buffer.
-
hhbuur
- Level 1
- Posts: 12
- Joined: Thu Feb 15, 2018 1:17 pm
Re: Make error
Post
by hhbuur » Sat Aug 11, 2018 1:12 pm
thanks fore your reply, that help.
can you help me white the next step, i am getting a messed when compelling and the compelling only make two file, «Module.symvers and modules.order» and both are empty.
Code: Select all
MJ # make
make -C /lib/modules/4.13.0-39-generic/build M=/home/MJ modules
make[1]: Entering directory '/usr/src/linux-headers-4.13.0-39-generic'
CC [M] /home/MJ/hello.o
/home/MJ/hello.c:1:2: error: invalid preprocessing directive #inClude
#inClude<linux/init.h>
^
/home/MJ/hello.c:2:2: error: invalid preprocessing directive #inClude
#inClude<linux/module.h>
^
/home/MJ/hello.c:4:16: error: expected declaration specifiers or ‘...’ before string constant
MODULE_LICENSE("GPL");
^
/home/MJ/hello.c:6:8: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘int’
statiC int hello_init(void)
^
/home/MJ/hello.c:12:8: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘void’
statiC void hello_exit(void)
^
/home/MJ/hello.c:17:1: warning: data definition has no type or storage class
module_init(hello_init);
^
/home/MJ/hello.c:17:1: error: type defaults to ‘int’ in declaration of ‘module_init’ [-Werror=implicit-int]
/home/MJ/hello.c:17:1: warning: parameter names (without types) in function declaration
/home/MJ/hello.c:18:1: warning: data definition has no type or storage class
module_exit(hello_exit);
^
/home/MJ/hello.c:18:1: error: type defaults to ‘int’ in declaration of ‘module_exit’ [-Werror=implicit-int]
/home/MJ/hello.c:18:1: warning: parameter names (without types) in function declaration
cc1: some warnings being treated as errors
scripts/Makefile.build:323: recipe for target '/home/MJ/hello.o' failed
make[2]: *** [/home/MJ/hello.o] Error 1
Makefile:1550: recipe for target '_module_/home/MJ' failed
make[1]: *** [_module_/home/MJ] Error 2
make[1]: Leaving directory '/usr/src/linux-headers-4.13.0-39-generic'
Makefile:5: recipe for target 'all' failed
make: *** [all] Error 2
hans MJ # vi Makefile
the Makefile
Code: Select all
obj-m +=hello.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
Linux Mint XFce 19.3
Lenovo ThinkPad W530 /2010
-
rene
- Level 20
- Posts: 11266
- Joined: Sun Mar 27, 2016 6:58 pm
Re: Make error
Post
by rene » Sat Aug 11, 2018 1:47 pm
You now have one obvious typo, again as pointed out by the error message: there’s no directive called «inClude». Let me just post the corrected hello.c.
Code: Select all
#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("GPL");
static int __init hello_init(void)
{
printk(KERN_ALERT "Hello worldn");
return 0;
}
static void __exit hello_exit(void)
{
printk(KERN_ALERT "Goodbyen");
}
module_init(hello_init);
module_exit(hello_exit);
Note that I added __init and __exit to to hello_init resp. hello_exit. Do not matter here but should be present generally: when the module’s built-in to the kernel __init causes a function to be placed in an after initialization discardable section of the kernel and __exit code is discarded outright.
Code: Select all
rene@hp8k ~/hello $ make
make -C /lib/modules/4.15.0-30-generic/build M=/home/rene/hello modules
make[1]: Entering directory '/usr/src/linux-headers-4.15.0-30-generic'
Makefile:976: "Cannot use CONFIG_STACK_VALIDATION=y, please install libelf-dev, libelf-devel or elfutils-libelf-devel"
CC [M] /home/rene/hello/hello.o
Building modules, stage 2.
MODPOST 1 modules
CC /home/rene/hello/hello.mod.o
LD [M] /home/rene/hello/hello.ko
make[1]: Leaving directory '/usr/src/linux-headers-4.15.0-30-generic'
rene@hp8k ~/hello $ sudo insmod ./hello.ko && sudo rmmod hello
[sudo] password for rene:
rene@hp8k ~/hello $ dmesg -t | tail -2
Hello world
Goodbye
Before those two lines dmesg will you telll that insmoding an unsigned module will taint your kernel. Module signing will undoubtedly, hopefully, be explained in the next section of whichever source you are consulting; if not, for now just ignore it.
[EDIT] For some odd reason, the module_init() and module_exit() got stripped from above paste of hello.c; added back again.
-
hhbuur
- Level 1
- Posts: 12
- Joined: Thu Feb 15, 2018 1:17 pm
Re: Make error
Post
by hhbuur » Sat Aug 18, 2018 8:04 am
I have come a little further but there is something I do not understand, in the manual there are printet three lines as a result while I only get one, or say otherwise it seems I do not get anything Array
the code
Code: Select all
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
MODULE_LICENSE("GPL");
int paramArray[3];
module_param_array(paramArray, int,NULL, S_IWUSR | S_IRUSR);
static int __init array_init(void)
{
printk("Into the parameter Array demon");
printk("Array elements are :%dt%dt%d",paramArray[0],paramArray[1],paramArray[2]);
return 0;
}
static void array_exit(void)
{
printk(KERN_ALERT "Exiting the array parameter demon");
}
module_init(array_init);
module_exit(array_exit);
make
Code: Select all
make
make -C /lib/modules/4.13.0-39-generic/build M=/home/MJ modules
make[1]: Entering directory '/usr/src/linux-headers-4.13.0-39-generic'
CC [M] /home/MJ/parameterArray.o
Building modules, stage 2.
MODPOST 1 modules
CC /home/MJ/parameterArray.mod.o
LD [M] /home/MJ/parameterArray.ko
make[1]: Leaving directory '/usr/src/linux-headers-4.13.0-39-generic'
the result
Code: Select all
sudo insmod parameterArray.ko paramArray=1,2,3
/home/MJ $ dmesg | tail -5
[ 58.076836] thinkpad_acpi: EC reports that Thermal Table has changed
[ 952.370581] INTO the parameter Array demo
[ 952.370583] Array elements are :1 2 3
[ 1555.760650] Exiting the array parameter demo
[ 1702.026904] INTO the parameter Array demo
Linux Mint XFce 19.3
Lenovo ThinkPad W530 /2010
-
rene
- Level 20
- Posts: 11266
- Joined: Sun Mar 27, 2016 6:58 pm
Re: Make error
Post
by rene » Sat Aug 18, 2018 8:34 am
hhbuur wrote: ↑
Sat Aug 18, 2018 8:04 am
[ … ] in the manual there are printet three lines as a result while I only get one
This is again the issue of you not flushing messages to the kernel message buffer; of you not ending the «Array elements are» printk() with a newline.
Two other remarks: while printk() has a default log level (KERN_WARNING normally) not explicitly specifying one as you do in but one instance is frowned upon. Also, if you mark your module_init() function __init consistency kindly requests you mark your module_exit() function __exit…
One additional remark… you may have in the form of this forum picked one of the worst possible places to go learn Linux kernel programming. It seems the kernelnewbies project is still alive: https://forum.kernelnewbies.org/ and/or https://kernelnewbies.org/ML. That would no doubt be a far better choice.
-
hhbuur
- Level 1
- Posts: 12
- Joined: Thu Feb 15, 2018 1:17 pm
Re: Make error
Post
by hhbuur » Thu Aug 23, 2018 8:42 am
ok i consider the problem sloved
Linux Mint XFce 19.3
Lenovo ThinkPad W530 /2010
Вопрос:
Я пытаюсь передать https://github.com/alexkay/xmonad-log-applet из GNOME2 в MATE, и до сих пор я получил прошлую конфигурацию и т.д., И я пытаюсь построить. Здесь вы можете найти мои изменения: https://github.com/geniass/xmonad-log-applet. Когда я запускаю make
, он начинает строить, но на последней строке он дает следующие ошибки:
main.c:92:39: error: expected declaration specifiers or ‘... before string constant
main.c:92:65: error: expected declaration specifiers or ‘... before ‘( token
main.c:92:84: error: expected declaration specifiers or ‘... before string constant
main.c:92:103: error: expected declaration specifiers or ‘... before ‘xmonad_log_applet_factory
main.c:92:130: error: expected declaration specifiers or ‘... before ‘( token
Я видел довольно много подобных вопросов здесь, в stackoverflow, но они в основном касались отказа от фигурных скобок или типов возвращаемых прототипов метода. Я не вижу здесь никого, но, может быть, я только что пропустил его? Помимо этой возможности, я совершенно не знаю, что может быть неправильным; эти ошибки совершенно бессмысленны для меня
Здесь main.c с удаленным ifdef для ясности (дает те же ошибки):
#include "config.h"
#include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
#include <dbus/dbus-glib.h>
#include <mate-panel-applet.h>
static void signal_handler(DBusGProxy *obj, const char *msg, GtkWidget *widget)
{
gtk_label_set_markup(GTK_LABEL(widget), msg);
}
static void set_up_dbus_transfer(GtkWidget *buf)
{
DBusGConnection *connection;
DBusGProxy *proxy;
GError *error= NULL;
connection = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
if(connection == NULL) {
g_printerr("Failed to open connection: %sn", error->message);
g_error_free(error);
exit(1);
}
proxy = dbus_g_proxy_new_for_name(
connection, "org.xmonad.Log", "/org/xmonad/Log", "org.xmonad.Log");
error = NULL;
dbus_g_proxy_add_signal(proxy, "Update", G_TYPE_STRING, G_TYPE_INVALID);
dbus_g_proxy_connect_signal(
proxy, "Update", (GCallback)signal_handler, buf, NULL);
}
static gboolean xmonad_log_applet_fill(MatePanelApplet *applet)
{
mate_panel_applet_set_flags(
applet,
MATE_PANEL_APPLET_EXPAND_MAJOR |
MATE_PANEL_APPLET_EXPAND_MINOR |
MATE_PANEL_APPLET_HAS_HANDLE);
mate_panel_applet_set_background_widget(applet, GTK_WIDGET(applet));
GtkWidget *label = gtk_label_new("Waiting for Xmonad...");
gtk_label_set_ellipsize(GTK_LABEL(label), PANGO_ELLIPSIZE_END);
gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.5);
set_up_dbus_transfer(label);
gtk_container_add(GTK_CONTAINER(applet), label);
gtk_widget_show_all(GTK_WIDGET(applet));
return TRUE;
}
static gboolean xmonad_log_applet_factory(
MatePanelApplet *applet, const gchar *iid, gpointer data)
{
gboolean retval = FALSE;
if(!strcmp(iid, "XmonadLogApplet"))
retval = xmonad_log_applet_fill(applet);
if(retval == FALSE) {
printf("Wrong applet!n");
exit(-1);
}
return retval;
}
MATE_PANEL_APPLET_OUT_PROCESS_FACTORY("XmonadLogAppletFactory", PANEL_TYPE_APPLET, "XmonadLogApplet", xmonad_log_applet_factory, NULL);
Лучший ответ:
Оказывается, я просто использовал старую версию библиотеки libmatepanel. Я использовал 2.0, тогда как текущая версия 3.0. По какой-то причине у меня есть как в моей системе
Ответ №1
Похоже, что вам не хватает include, который предоставляет определение MATE_PANEL_APPLET_OUT_PROCESS_FACTORY
I am new to devkitpro and am looking to make switch homebrew. I have tried to make the examples and have received errors. I don’t really know what is wrong with it
Code: Select all
MSYS /c/devkitpro/examples/switch/graphics/printing/hello-world
$ make
main.c
aarch64-none-elf-gcc -MMD -MP -MF /c/devkitpro/examples/switch/graphics/printing/hello-world/build/main.d -g -Wall -O2 -ffunction-sections -march=armv8-a -mtune=cortex-a57 -mtp=soft -fPIE -I/c/devkitpro/examples/switch/graphics/printing/hello-world/include -I/opt/devkitpro/portlibs/switch/include -I/opt/devkitpro/libnx/include -I/c/devkitpro/examples/switch/graphics/printing/hello-world/build -D__SWITCH__ -c /c/devkitpro/examples/switch/graphics/printing/hello-world/source/main.c -o main.o
In file included from C:/devkitPro/libnx/include/switch.h:49,
from C:/devkitpro/examples/switch/graphics/printing/hello-world/source/main.c:4:
C:/devkitPro/libnx/include/switch/services/hid.h:356:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidTouchScreenHeader) == 0x28, "Hid touch screen header structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:356:53: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidTouchScreenHeader) == 0x28, "Hid touch screen header structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:363:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidTouchScreenEntryHeader) == 0x10, "Hid touch screen entry header structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:363:58: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidTouchScreenEntryHeader) == 0x10, "Hid touch screen entry header structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:377:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidTouchScreenEntryTouch) == 0x28, "Hid touch screen touch structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:377:57: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidTouchScreenEntryTouch) == 0x28, "Hid touch screen touch structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:385:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidTouchScreenEntry) == 0x298, "Hid touch screen entry structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:385:53: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidTouchScreenEntry) == 0x298, "Hid touch screen entry structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:393:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidTouchScreen) == 0x3000, "Hid touch screen structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:393:49: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidTouchScreen) == 0x3000, "Hid touch screen structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:406:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidMouseHeader) == 0x20, "Hid mouse header structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:406:47: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidMouseHeader) == 0x20, "Hid mouse header structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:415:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidMouseEntry) == 0x30, "Hid mouse entry structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:415:46: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidMouseEntry) == 0x30, "Hid mouse entry structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:423:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidMouse) == 0x400, "Hid mouse structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:423:42: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidMouse) == 0x400, "Hid mouse structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:436:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidKeyboardHeader) == 0x20, "Hid keyboard header structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:436:50: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidKeyboardHeader) == 0x20, "Hid keyboard header structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:445:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidKeyboardEntry) == 0x38, "Hid keyboard entry structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:445:49: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidKeyboardEntry) == 0x38, "Hid keyboard entry structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:453:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidKeyboard) == 0x400, "Hid keyboard structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:453:45: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidKeyboard) == 0x400, "Hid keyboard structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:466:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidControllerMAC) == 0x20, "Hid controller MAC structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:466:49: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidControllerMAC) == 0x20, "Hid controller MAC structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:481:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidControllerHeader) == 0x28, "Hid controller header structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:481:52: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidControllerHeader) == 0x28, "Hid controller header structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:490:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidControllerLayoutHeader) == 0x20, "Hid controller layout header structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:490:58: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidControllerLayoutHeader) == 0x20, "Hid controller layout header structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:500:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidControllerInputEntry) == 0x30, "Hid controller input entry structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:500:56: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidControllerInputEntry) == 0x30, "Hid controller input entry structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:507:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidControllerLayout) == 0x350, "Hid controller layout structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:507:53: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidControllerLayout) == 0x350, "Hid controller layout structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:518:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidController) == 0x5000, "Hid controller structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:518:48: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidController) == 0x5000, "Hid controller structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:540:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidSharedMemory) == 0x40000, "Hid Shared Memory structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:540:51: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidSharedMemory) == 0x40000, "Hid Shared Memory structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:547:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidVibrationDeviceInfo) == 0x8, "Hid VibrationDeviceInfo structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:547:54: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidVibrationDeviceInfo) == 0x8, "Hid VibrationDeviceInfo structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:556:15: error: expected declaration specifiers or '...' before 'sizeof'
static_assert(sizeof(HidVibrationValue) == 0x10, "Hid VibrationValue structure has incorrect size");
^~~~~~
C:/devkitPro/libnx/include/switch/services/hid.h:556:50: error: expected declaration specifiers or '...' before string constant
static_assert(sizeof(HidVibrationValue) == 0x10, "Hid VibrationValue structure has incorrect size");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from C:/devkitPro/libnx/include/switch.h:72,
from C:/devkitpro/examples/switch/graphics/printing/hello-world/source/main.c:4:
C:/devkitPro/libnx/include/switch/runtime/util/utf.h:19:1: error: unknown type name 'ssize_t'; did you mean 'size_t'?
ssize_t decode_utf8 (uint32_t *out, const uint8_t *in);
^~~~~~~
size_t
C:/devkitPro/libnx/include/switch/runtime/util/utf.h:29:1: error: unknown type name 'ssize_t'; did you mean 'size_t'?
ssize_t decode_utf16(uint32_t *out, const uint16_t *in);
^~~~~~~
size_t
C:/devkitPro/libnx/include/switch/runtime/util/utf.h:41:1: error: unknown type name 'ssize_t'; did you mean 'size_t'?
ssize_t encode_utf8 (uint8_t *out, uint32_t in);
^~~~~~~
size_t
C:/devkitPro/libnx/include/switch/runtime/util/utf.h:53:1: error: unknown type name 'ssize_t'; did you mean 'size_t'?
ssize_t encode_utf16(uint16_t *out, uint32_t in);
^~~~~~~
size_t
C:/devkitPro/libnx/include/switch/runtime/util/utf.h:71:1: error: unknown type name 'ssize_t'; did you mean 'size_t'?
ssize_t utf8_to_utf16(uint16_t *out, const uint8_t *in, size_t len);
^~~~~~~
size_t
C:/devkitPro/libnx/include/switch/runtime/util/utf.h:89:1: error: unknown type name 'ssize_t'; did you mean 'size_t'?
ssize_t utf8_to_utf32(uint32_t *out, const uint8_t *in, size_t len);
^~~~~~~
size_t
C:/devkitPro/libnx/include/switch/runtime/util/utf.h:107:1: error: unknown type name 'ssize_t'; did you mean 'size_t'?
ssize_t utf16_to_utf8(uint8_t *out, const uint16_t *in, size_t len);
^~~~~~~
size_t
C:/devkitPro/libnx/include/switch/runtime/util/utf.h:125:1: error: unknown type name 'ssize_t'; did you mean 'size_t'?
ssize_t utf16_to_utf32(uint32_t *out, const uint16_t *in, size_t len);
^~~~~~~
size_t
C:/devkitPro/libnx/include/switch/runtime/util/utf.h:143:1: error: unknown type name 'ssize_t'; did you mean 'size_t'?
ssize_t utf32_to_utf8(uint8_t *out, const uint32_t *in, size_t len);
^~~~~~~
size_t
C:/devkitPro/libnx/include/switch/runtime/util/utf.h:156:1: error: unknown type name 'ssize_t'; did you mean 'size_t'?
ssize_t utf32_to_utf16(uint16_t *out, const uint32_t *in, size_t len);
^~~~~~~
size_t
In file included from C:/devkitPro/libnx/include/switch.h:76,
from C:/devkitpro/examples/switch/graphics/printing/hello-world/source/main.c:4:
C:/devkitPro/libnx/include/switch/runtime/devices/fs_dev.h:20:3: error: unknown type name 'ssize_t'
ssize_t index; ///< Current entry index
^~~~~~~
make[1]: *** [/opt/devkitpro/devkitA64/base_rules:19: main.o] Error 1
make: *** [Makefile:148: build] Error 2
Я пытаюсь создать функцию журнала, которая будет принимать тип журнала, msg и добавлять имя файла, имя функции, строку, из которой была вызвана функция журнала. Я создал следующий тестовый код, но получаю непонятные мне ошибки.
#include<stdio.h> #define func(type, msg, ...) func(type, __FILE__, __func__, __LINE__, msg, __VA_ARGS__) void func(int type, const char *file, const char *function, int line, const char *msg, ...) { printf("%s",msg); } main() { func(10,"time"); }
Вот журнал ошибок:
||=== Build file: "no target" in "no project" (compiler: unknown) ===| E:codeC codeA.c|6|error: expected declaration specifiers or '...' before string constant| E:codeC codeA.c|3|error: expected declaration specifiers or '...' before '__func__'| E:codeC codeA.c|6|note: in expansion of macro 'func'| E:codeC codeA.c|6|error: expected declaration specifiers or '...' before numeric constant| E:codeC codeA.c|6|warning: type defaults to 'int' in declaration of 'msg' [-Wimplicit-int]| E:codeC codeA.c|3|note: in definition of macro 'func'| E:codeC codeA.c|12|warning: return type defaults to 'int' [-Wimplicit-int]| E:codeC codeA.c||In function 'main':| E:codeC codeA.c|3|warning: implicit declaration of function 'func' [-Wimplicit-function- declaration]| E:codeC codeA.c|15|note: in expansion of macro 'func'| E:codeC codeA.c|3|error: expected expression before ')' token| E:codeC codeA.c|15|note: in expansion of macro 'func'| ||=== Build failed: 4 error(s), 3 warning(s) (0 minute(s), 0 second(s)) ===|
Я прочитал этот вопрос, но Я не могу связать решения с моим кодом.
1 ответ
Лучший ответ
Ваш код может быть разумным:
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
extern void (logger)(int type, const char *file, const char *function, int line, const char *fmt, ...);
#define logger(type, msg, ...) logger(type, __FILE__, __func__, __LINE__, msg, __VA_ARGS__)
void (logger)(int type, const char *file, const char *function, int line, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
printf("%s:%d:%s() - %d: ", file, line, function, type);
vprintf(fmt, args);
va_end(args);
}
int main(void)
{
logger(10, "time %ldn", (long)time(0));
}
Дополнительный аргумент необходим для того, чтобы __VA_ARGS__
было на что ссылаться. См. Макрос #define
для отладочной печати на C за обширное обсуждение. Самым простым переносимым исправлением, вероятно, является изменение макроса, чтобы включить строку формата как часть __VA_ARGS__
.
#define logger(type, ...) logger(type, __FILE__, __func__, __LINE__, __VA_ARGS__)
С этим изменением вы можете использовать это еще раз:
int main(void)
{
logger(10, "timen");
}
Вероятно, лучше отделить имя макроса, который люди будут использовать (logger
) от имени функции (например, logger_loc
, где loc
указывает на информацию о «местоположении»). Однако знающий пользователь может написать (logger)(10, "elephants.c", "pachyderm", 31921, "timen");
, если он хочет вызвать функцию напрямую. Поскольку за logger
сразу не следует токен (
, это не вызов функционально-подобного макроса logger
.
Существует также специальный обходной путь для GCC для проблемы «отсутствующего __VA_ARGS__
«, и C ++ 20 также работал над этой проблемой и создал другое решение (см. Переносно обнаруживать __VA_OPT__
поддержку? ), которая, как я ожидаю, вероятно, появится в будущем стандарте C (и в компиляторах C до этого гипотетический будущий стандарт C).
1
Jonathan Leffler
29 Дек 2019 в 10:39
Does anybody know what is wrong with this piece of code? i can’t see to find the issue among the comparable questions.
The code is written in C, and i keep getting this error. I do add -D SET_MIN_TEMP=5 -D Set_MAX_TEMP=30
to the gcc compile line to make sure the ifndefs should be false…
#ifndef CONFIG_H
#define CONFIG_H
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdint.h>
#ifndef RUN_AVG_LENGTH
#define RUN_AVG_LENGTH 5
#endif
#ifndef SET_MIN_TEMP
printf("please set SET_MIN_TEMP n");
#endif
#ifndef SET_MAX_TEMP
printf("please set SET_MAX_TEMP n");
#endif
typedef uint16_t sensor_id_t;
typedef uint16_t room_id_t;
typedef double sensor_value_t;
typedef time_t sensor_ts_t; // UTC timestamp as returned by time() - notice that the size of time_t is different on 32/64 bit machine
typedef struct {
sensor_id_t id;
sensor_value_t value;
sensor_ts_t ts;
} sensor_data_t;
typedef struct {
sensor_id_t sensor_id;
room_id_t room_id;
double running_avg[5];
sensor_ts_t timestamp;
} sensor_node_t;
#endif // CONFIG_H
Barmar
718k53 gold badges481 silver badges598 bronze badges
asked Apr 13, 2016 at 18:30
6
You can not use a function call (printf
) outside a function. You should take a look at #error
if you want to report errors at compilation…
See here
answered Apr 13, 2016 at 18:35
mame98mame98
1,23115 silver badges26 bronze badges
5
I am getting an error on a specific line that mimics the usage in another file.
PyObject *pyCharGetHeight(PyChar *self, void *closure) {
CHAR_DATA *ch = PyChar_AsChar((PyObject *)self);
PyObject *height = NULL;
if(ch != NULL) height = Py_BuildValue("s", charGetHeight(ch));
return height;
}
PyChar_addGetSetter("height", pyCharGetHeight, NULL, "Returns character's height");
is returning the following error, PyChar_addGetSetter… line
error: expected declaration specifiers or â…â before string constant
I am using the following includes:
#include <Python.h>
#include "../scripts/pychar.h"
And pychar.h does define PyChar_addGetSetter() as prototyped here:
void PyChar_addGetSetter(const char *name, void *g, void *s, const char *doc);
The function is written in ../scripts/pychar.c as follows:
void PyChar_addGetSetter(const char *name, void *g, void *s, const char *doc) {
// make sure our list of get/setters is created
if(pychar_getsetters == NULL) pychar_getsetters = newList();
// make the GetSetter def
PyGetSetDef *def = calloc(1, sizeof(PyGetSetDef));
def->name = strdup(name);
def->get = (getter)g;
def->set = (setter)s;
def->doc = (doc ? strdup(doc) : NULL);
def->closure = NULL;
listPut(pychar_getsetters, def);
}
It seems like a structure or type is not being recognized, I am guessing my function.
I had the same problem. My error messages were:
TarHeader.h:15:24: error: expected declaration specifiers or '...' before numeric constant TarHeader.c:69:61: error: expected declaration specifiers or '...' before string constant
And the specific lines of code were:
* Line 15 in TarHeader.h:
#define TAR_BLOCK_SIZE 512
* Line 69 (v1) in TarHeader.c:
static_assert(TAR_BLOCK_SIZE == sizeof(tar_posix_header_t), "Incorrect header definition");
When I tried to change it I changed the includes in «TarHeader.c» (removed include of «TarHeader.h»)
The line seems then like this (Line 69 (v2) in TarHeader.c)
static_assert(512== sizeof(tar_posix_header_t), "Incorrect header definition");
And the error codes changed:
TarHeader.c:69:15: error: expected declaration specifiers or '...' before numeric constant TarHeader.c:69:50: error: expected declaration specifiers or '...' before string constant
When I removed line 65 of «TarHeader.c» no error was reported even with the previously used include.
The static assert was copied from another project (also in C) ane there was no problem. But it was a different compiler.
Solution:
Search for the use of these defines and see what use causes this problem.
Forum rules
Before you post please read how to get help. Topics in this forum are automatically closed 6 months after creation.
-
hhbuur
- Level 1
- Posts: 12
- Joined: Thu Feb 15, 2018 1:17 pm
[SOLVED]Make error
Can I get some help with understand these error messages. I am trying to make a hello world.
#include<linux/init.h>
#include<linux/module.h>MODUL_LICENSE(«GPL»);
static int hello_init(void)
{
printk(KERN_ALERT «Hello world»);
retur 0;
}static void hello_exit(void)
{
printk(KERN_Alert «Goodby»);
}module_init(hello_init);
module_exit(hello_exit);obj-m +=hello.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
hhb # make
make -C /lib/modules/4.13.0-39-generic/build M=/home/hans/hhb modules
make[1]: Entering directory ‘/usr/src/linux-headers-4.13.0-39-generic’
CC [M] /home/hans/hhb/hello.o
/home/hans/hhb/hello.c:4:15: error: expected declaration specifiers or ‘…’ before string constant
MODUL_LICENSE(«GPL»);
^
/home/hans/hhb/hello.c: In function ‘hello_init’:
/home/hans/hhb/hello.c:9:1: error: ‘retur’ undeclared (first use in this function)
retur 0;
^
/home/hans/hhb/hello.c:9:1: note: each undeclared identifier is reported only once for each function it appears in
/home/hans/hhb/hello.c:9:7: error: expected ‘;’ before numeric constant
retur 0;
^
/home/hans/hhb/hello.c:10:1: warning: no return statement in function returning non-void [-Wreturn-type]
}
^
/home/hans/hhb/hello.c: In function ‘hello_exit’:
/home/hans/hhb/hello.c:14:8: error: ‘KERN_Alert’ undeclared (first use in this function)
printk(KERN_Alert «Goodby»);
^
/home/hans/hhb/hello.c:14:19: error: expected ‘)’ before string constant
printk(KERN_Alert «Goodby»);
^
scripts/Makefile.build:323: recipe for target ‘/home/hans/hhb/hello.o’ failed
make[2]: *** [/home/hans/hhb/hello.o] Error 1
Makefile:1550: recipe for target ‘_module_/home/hans/hhb’ failed
make[1]: *** [_module_/home/hans/hhb] Error 2
make[1]: Leaving directory ‘/usr/src/linux-headers-4.13.0-39-generic’
Makefile:4: recipe for target ‘all’ failed
make: *** [all] Error 2
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 2 times in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
Linux Mint XFce 19.3
Lenovo ThinkPad W530 /2010
-
rene
- Level 20
- Posts: 11402
- Joined: Sun Mar 27, 2016 6:58 pm
Re: Make error
Post
by rene » Sat Jul 28, 2018 4:49 pm
You have 3 obvious typo’s, all of which are pointed out by the error messages. Modulo module signing, the only thing that’s otherwise wrong is that you should end your printk strings with «n» so as to flush them to the kernel message buffer.
-
hhbuur
- Level 1
- Posts: 12
- Joined: Thu Feb 15, 2018 1:17 pm
Re: Make error
Post
by hhbuur » Sat Aug 11, 2018 1:12 pm
thanks fore your reply, that help.
can you help me white the next step, i am getting a messed when compelling and the compelling only make two file, «Module.symvers and modules.order» and both are empty.
Code: Select all
MJ # make
make -C /lib/modules/4.13.0-39-generic/build M=/home/MJ modules
make[1]: Entering directory '/usr/src/linux-headers-4.13.0-39-generic'
CC [M] /home/MJ/hello.o
/home/MJ/hello.c:1:2: error: invalid preprocessing directive #inClude
#inClude<linux/init.h>
^
/home/MJ/hello.c:2:2: error: invalid preprocessing directive #inClude
#inClude<linux/module.h>
^
/home/MJ/hello.c:4:16: error: expected declaration specifiers or ‘...’ before string constant
MODULE_LICENSE("GPL");
^
/home/MJ/hello.c:6:8: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘int’
statiC int hello_init(void)
^
/home/MJ/hello.c:12:8: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘void’
statiC void hello_exit(void)
^
/home/MJ/hello.c:17:1: warning: data definition has no type or storage class
module_init(hello_init);
^
/home/MJ/hello.c:17:1: error: type defaults to ‘int’ in declaration of ‘module_init’ [-Werror=implicit-int]
/home/MJ/hello.c:17:1: warning: parameter names (without types) in function declaration
/home/MJ/hello.c:18:1: warning: data definition has no type or storage class
module_exit(hello_exit);
^
/home/MJ/hello.c:18:1: error: type defaults to ‘int’ in declaration of ‘module_exit’ [-Werror=implicit-int]
/home/MJ/hello.c:18:1: warning: parameter names (without types) in function declaration
cc1: some warnings being treated as errors
scripts/Makefile.build:323: recipe for target '/home/MJ/hello.o' failed
make[2]: *** [/home/MJ/hello.o] Error 1
Makefile:1550: recipe for target '_module_/home/MJ' failed
make[1]: *** [_module_/home/MJ] Error 2
make[1]: Leaving directory '/usr/src/linux-headers-4.13.0-39-generic'
Makefile:5: recipe for target 'all' failed
make: *** [all] Error 2
hans MJ # vi Makefile
the Makefile
Code: Select all
obj-m +=hello.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
Linux Mint XFce 19.3
Lenovo ThinkPad W530 /2010
-
rene
- Level 20
- Posts: 11402
- Joined: Sun Mar 27, 2016 6:58 pm
Re: Make error
Post
by rene » Sat Aug 11, 2018 1:47 pm
You now have one obvious typo, again as pointed out by the error message: there’s no directive called «inClude». Let me just post the corrected hello.c.
Code: Select all
#include <linux/init.h>
#include <linux/module.h>
MODULE_LICENSE("GPL");
static int __init hello_init(void)
{
printk(KERN_ALERT "Hello worldn");
return 0;
}
static void __exit hello_exit(void)
{
printk(KERN_ALERT "Goodbyen");
}
module_init(hello_init);
module_exit(hello_exit);
Note that I added __init and __exit to to hello_init resp. hello_exit. Do not matter here but should be present generally: when the module’s built-in to the kernel __init causes a function to be placed in an after initialization discardable section of the kernel and __exit code is discarded outright.
Code: Select all
rene@hp8k ~/hello $ make
make -C /lib/modules/4.15.0-30-generic/build M=/home/rene/hello modules
make[1]: Entering directory '/usr/src/linux-headers-4.15.0-30-generic'
Makefile:976: "Cannot use CONFIG_STACK_VALIDATION=y, please install libelf-dev, libelf-devel or elfutils-libelf-devel"
CC [M] /home/rene/hello/hello.o
Building modules, stage 2.
MODPOST 1 modules
CC /home/rene/hello/hello.mod.o
LD [M] /home/rene/hello/hello.ko
make[1]: Leaving directory '/usr/src/linux-headers-4.15.0-30-generic'
rene@hp8k ~/hello $ sudo insmod ./hello.ko && sudo rmmod hello
[sudo] password for rene:
rene@hp8k ~/hello $ dmesg -t | tail -2
Hello world
Goodbye
Before those two lines dmesg will you telll that insmoding an unsigned module will taint your kernel. Module signing will undoubtedly, hopefully, be explained in the next section of whichever source you are consulting; if not, for now just ignore it.
[EDIT] For some odd reason, the module_init() and module_exit() got stripped from above paste of hello.c; added back again.
-
hhbuur
- Level 1
- Posts: 12
- Joined: Thu Feb 15, 2018 1:17 pm
Re: Make error
Post
by hhbuur » Sat Aug 18, 2018 8:04 am
I have come a little further but there is something I do not understand, in the manual there are printet three lines as a result while I only get one, or say otherwise it seems I do not get anything Array
the code
Code: Select all
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
MODULE_LICENSE("GPL");
int paramArray[3];
module_param_array(paramArray, int,NULL, S_IWUSR | S_IRUSR);
static int __init array_init(void)
{
printk("Into the parameter Array demon");
printk("Array elements are :%dt%dt%d",paramArray[0],paramArray[1],paramArray[2]);
return 0;
}
static void array_exit(void)
{
printk(KERN_ALERT "Exiting the array parameter demon");
}
module_init(array_init);
module_exit(array_exit);
make
Code: Select all
make
make -C /lib/modules/4.13.0-39-generic/build M=/home/MJ modules
make[1]: Entering directory '/usr/src/linux-headers-4.13.0-39-generic'
CC [M] /home/MJ/parameterArray.o
Building modules, stage 2.
MODPOST 1 modules
CC /home/MJ/parameterArray.mod.o
LD [M] /home/MJ/parameterArray.ko
make[1]: Leaving directory '/usr/src/linux-headers-4.13.0-39-generic'
the result
Code: Select all
sudo insmod parameterArray.ko paramArray=1,2,3
/home/MJ $ dmesg | tail -5
[ 58.076836] thinkpad_acpi: EC reports that Thermal Table has changed
[ 952.370581] INTO the parameter Array demo
[ 952.370583] Array elements are :1 2 3
[ 1555.760650] Exiting the array parameter demo
[ 1702.026904] INTO the parameter Array demo
Linux Mint XFce 19.3
Lenovo ThinkPad W530 /2010
-
rene
- Level 20
- Posts: 11402
- Joined: Sun Mar 27, 2016 6:58 pm
Re: Make error
Post
by rene » Sat Aug 18, 2018 8:34 am
hhbuur wrote: ↑
Sat Aug 18, 2018 8:04 am
[ … ] in the manual there are printet three lines as a result while I only get one
This is again the issue of you not flushing messages to the kernel message buffer; of you not ending the «Array elements are» printk() with a newline.
Two other remarks: while printk() has a default log level (KERN_WARNING normally) not explicitly specifying one as you do in but one instance is frowned upon. Also, if you mark your module_init() function __init consistency kindly requests you mark your module_exit() function __exit…
One additional remark… you may have in the form of this forum picked one of the worst possible places to go learn Linux kernel programming. It seems the kernelnewbies project is still alive: https://forum.kernelnewbies.org/ and/or https://kernelnewbies.org/ML. That would no doubt be a far better choice.
-
hhbuur
- Level 1
- Posts: 12
- Joined: Thu Feb 15, 2018 1:17 pm
Re: Make error
Post
by hhbuur » Thu Aug 23, 2018 8:42 am
ok i consider the problem sloved
Linux Mint XFce 19.3
Lenovo ThinkPad W530 /2010
0
0
Добрый день!
При компиляции libpcap возникла непонятная ошибка:
gcc -nodefaultlibs -nostdlib -fPIC -static -I/home/xvilka/build/cross/sys-root/usr/include -O2
-fPIC -nodefaultlibs -nostdlib -fPIC -static -I/home/xvilka/build/cross/sys-root/usr/include -I.
-DHAVE_CONFIG_H -D_U_="__attribute__((unused))" -c ./pcap-usb-linux.c
In file included from ./pcap-usb-linux.c:57:
/home/xvilka/build/cross/sys-root/usr/include/string.h:431: error: expected declaration specifiers or '...' before '(' token
/home/xvilka/build/cross/sys-root/usr/include/string.h:431: error: expected declaration specifiers or '...' before '(' token
/home/xvilka/build/cross/sys-root/usr/include/string.h:431: error: expected declaration specifiers or '...' before '(' token
/home/xvilka/build/cross/sys-root/usr/include/string.h:431: error: expected ')' before ',' token
make[1]: *** [pcap-usb-linux.o] Error 1
В чем может быть проблема? (такую ошибку в первый раз встречаю)
Некоторые флаги компилятора повторяются, хотя при .configure были заданы один раз, но уверен это не играет здесь роли.
Помогите с решением, спасибо!
На чтение 2 мин Обновлено 18.01.2023
Arch Linux
You are not logged in.
#1 2012-07-31 08:48:08
[SOLVED] Problem with GCC
Hi guys!
I have a problem with gcc.
I’m trying to learn how to program sockets using C.
So i followed a tuotrial and i wrote up a little client server, but when i try to compile it i can’t do it.
These is the client:
When i try to compile it i got many errors. I don’t know why, i followed a tutorial so the code should be corrected.
These is the output:
Last edited by Ananke (2012-07-31 13:36:37)
#2 2012-07-31 08:56:54
Re: [SOLVED] Problem with GCC
Is this your actual code?
You forgot the semicolon after «int CSocket», then.
This was the hint in the error messages:
To know or not to know .
. the questions remain forever.
#3 2012-07-31 11:18:04
Re: [SOLVED] Problem with GCC
Yup, also the first error tells you what is missing. When you get error output while compiling always focus on the first error message. Often one error early in the code can lead to lots of other problems, so the first error message tells you what to fix.
Additionally, while there are many different coding «styles» I don’t know of any that don’t use indentation to highlight the structure of the code. That would make this code much easier to read.
«UNIX is simple and coherent. » — Dennis Ritchie, «GNU’s Not UNIX» — Richard Stallman
Online
#4 2012-07-31 11:45:36
Re: [SOLVED] Problem with GCC
Thank you for help guys.
I’m not really good with english language and i don’t understand what «semicolon after int Csocket» means. May you explain me how i should modify the code?
I use Geany as editor, so i can see the higlight of sintax with colours. If you want here is the code with highlighting:
http://pastebin.com/fdci4mPk
Last edited by Ananke (2012-07-31 13:12:36)
Источник
Ожидаемые спецификаторы объявления или ‘…’ перед строковой константой
я осознаю Expected declaration specifiers or '...' before string constant
ошибка в mach_override.c in проект scplugin во второй строке кода ниже.
asm(
".text;"
".align 2, 0x90;"
".globl _atomic_mov64;"
"_atomic_mov64:;"
" pushl %ebp;"
" movl %esp, %ebp;"
" pushl %esi;"
" pushl %ebx;"
" pushl %ecx;"
" pushl %eax;"
" pushl %edx;"
// atomic push of value to an address
// we use cmpxchg8b, which compares content of an address with
// edx:eax. If they are equal, it atomically puts 64bit value
// ecx:ebx in address.
// We thus put contents of address in edx:eax to force ecx:ebx
// in address
" mov 8(%ebp), %esi;" // esi contains target address
" mov 12(%ebp), %ebx;"
" mov 16(%ebp), %ecx;" // ecx:ebx now contains value to put in target address
" mov (%esi), %eax;"
" mov 4(%esi), %edx;" // edx:eax now contains value currently contained in target address
" lock; cmpxchg8b (%esi);" // atomic move.
// restore registers
" popl %edx;"
" popl %eax;"
" popl %ecx;"
" popl %ebx;"
" popl %esi;"
" popl %ebp;"
" ret"
);
Allow asm, inline typeof
Флаг установлен в моих настройках сборки. кто-нибудь может мне помочь?
Сделайте следующее изменение (во флагах):
C language dialect = Compiler Default
Создан 02 янв.
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
objective-c
xcode
gcc
inline-assembly
or задайте свой вопрос.
remzona 1 / 1 / 0 Регистрация: 03.07.2016 Сообщений: 58 |
||||||||
1 |
||||||||
Модуль ядра, некорректная работа15.07.2020, 08:49. Показов 1627. Ответов 8 Метки нет (Все метки)
Здравствуйте!, изучаю тему написания модулей ядра. Начал с Hello, world.
Естетсвенно после insmod я ожидаю Starting… в syslog и Exit… после rmmod, но вывод получается наоборот:
В чём моя ошибка?
__________________ 0 |
550 / 383 / 125 Регистрация: 02.10.2008 Сообщений: 1,553 Записей в блоге: 1 |
|
17.07.2020, 21:46 |
2 |
Какое ядро? Как компилишь? 0 |
308 / 168 / 46 Регистрация: 18.10.2017 Сообщений: 1,585 |
|
18.07.2020, 17:20 |
3 |
drfaust, сам пример очень устаревший. И что, это всё содержимое? 0 |
1 / 1 / 0 Регистрация: 03.07.2016 Сообщений: 58 |
|
28.07.2020, 08:45 [ТС] |
4 |
Прошу прощения за долгое отсутствие, проблема решилась сама собой. Мне пояснили, что всё дело в буферизации вывода, это можно исправить. Правда пока не рассказали как 0 |
drfaust 550 / 383 / 125 Регистрация: 02.10.2008 Сообщений: 1,553 Записей в блоге: 1 |
||||
28.07.2020, 19:53 |
5 |
|||
Сообщение было отмечено remzona как решение РешениеПопробуй
По идее, перевод строки может сбросить буфер 1 |
Dexel 46 / 13 / 3 Регистрация: 29.09.2013 Сообщений: 289 |
||||
24.09.2020, 19:59 |
6 |
|||
Код # dmesg -c [13284.673059] Starting module... [13604.719906] Exit module... Добавлено через 13 минут 0 |
drfaust 550 / 383 / 125 Регистрация: 02.10.2008 Сообщений: 1,553 Записей в блоге: 1 |
||||
24.09.2020, 20:03 |
7 |
|||
Dexel, Хм…
0 |
Dexel 46 / 13 / 3 Регистрация: 29.09.2013 Сообщений: 289 |
||||||||
24.09.2020, 21:01 |
8 |
|||||||
Даже на printk ругается… оригинально. Та может на арче ядро другое, не знаю. У ТС тоже нормально компилит.
Добавлено через 47 минут
Код # insmod modulehelloworld.ko # dmesg -c [18251.333649] Starting module... # rmmod modulehelloworld # dmesg -c [18259.893036] Exit module... 1 |
550 / 383 / 125 Регистрация: 02.10.2008 Сообщений: 1,553 Записей в блоге: 1 |
|
26.09.2020, 22:05 |
9 |
Уже пытался объяснить… Добавлено через 2 минуты
Даже на printk ругается… оригинально. Ну если другие модули дрова компилятся из сырцов — то всё в норм, но я make не писал — тупо gcc зарядил… 0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
26.09.2020, 22:05 |
9 |