Error expected identifier or before numeric constant

I have this header file ... for some reason I keep getting an error saying log_server.h:48: error: expected identifier or ‘(’ before numeric constant I get this error on both lines defining the pu...

I have this header file … for some reason I keep getting an error saying
log_server.h:48: error: expected identifier or ‘(’ before numeric constant
I get this error on both lines defining the put_evt and print_evt_list functions,
here’s what the code looks like:

#ifndef _GENERIC
#define _GENERIC
#include <string.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#endif

#ifndef _NETWORKING
#define _NETWORKING
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
typedef struct sockaddr SA;/* To make casting in the (bind, recvfrom, sendto) more readable */
#endif

#define LOGIN_EVT 0
#define LOGOUT_EVT 1

#define RECV_MSG 27
#define SEND_MSG 64000
#define MAX_EVT_COUNT 3000

struct evt{ 
    char user_name[8];
    int type;
    long int time;
};



/* open log file to append the events to its end
 * return 0 on success and -1 on failure (file could not be opened)
 */
int init_log(const char *log_fname);

/* closes the log file
 * return 0 on success and -1 on failure (file could not be opened)
 */
int terminate_log();

/* add new event to the log file
 * return 0 on success and -1 on failure
 */
int put_evt(struct evt *e);

/* get list of events that occured after the given time
 * count is the size of the allocated and passed e-list
 * return number of found events on success and -1 on failure
 */
int get_events(struct evt  *e_list, long int time);

/* print given event's info (name, time)*/
void print_evt(struct evt  *e);

/* print "count" event's info from the given e_list info (name, time)*/
void print_evt_list(struct evt  *e_list, int count);

/* startListen takes a port number and returns a listening descriptor on sucess or negavtive on error  */
int startListen(int port);

/* Responsbile for hanlding received messages from clients and responding to them accordingly
if the message is an action done, it'll save it in the log file and notify the client
if the message is a query about the events, it'll call the private function queryHandler(); to handle it
returns negative on ERROR*/
int handle_message(int sockDescriptor, struct sockaddr_in *client, char *recvMessage);

I’ve read that this error can be caused by having a preprocessing directive written on more than one line … but I don’t have that. Any idea what I’m doing wrong?

Centavrianin

0 / 0 / 0

Регистрация: 11.07.2016

Сообщений: 2

1

11.07.2016, 21:02. Показов 15852. Ответов 4

Метки нет (Все метки)


Здравствуйте! Просьба помочь разобраться с ошибкой.

Изучаю Си по книге Б. Кернигана и Д. Ритчи «Язык программирования Си». Переписал очередной пример из книги, но при попытке скомпилировать код выходит сообщение об ошибке:

Bash
1
2
3
4
5
6
user@user-mint ~/progs $ gcc maxline.c
maxline.c:2:17: error: expected ‘;’, ‘,’ or ‘)’ before numeric constant
 #define MAXLINE 1000 /*максимальный размер вводимой строки*/
                 ^
maxline.c:4:34: note: in expansion of macro ‘MAXLINE’
 int getline_max(char line[], int MAXLINE);

Сам код:

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <stdio.h>
#define MAXLINE 1000 /*максимальный размер вводимой строки*/
 
int getline_max(char line[], int MAXLINE);
void copy_max(char to[], char from[]);
 
main()
{
    int len; /* длина текущей строки */
    int max; /* длина максимальной из просмотренных строк */
    char line[MAXLINE]; /* массив текущей строки */
    char longest[MAXLINE]; /* массив самой длинной строки */
    max = 0;
    while ((len = getline_max(line, MAXLINE)) > 0)
        if (len > max){
            max = len;
            copy_max(longest, line);
        }
    if (max > 0) /* была ли хоть одна строка? */
        printf("%s", longest);
    return 0;
}
 
 
/* getline: читает строку в s, возвращает длину */
int getline_max(char s[], int lim)
{
    int c, i;
    for (i = 0; i < lim-1 && ((c = getchar()) != 'n') && c != EOF; ++i)
        s[i] = c;
    if (c == 'n') {
        s[i] = c;
        ++i;
    }
    s[i] = '';
    return i;
}
 
/* copy: копирует из 'from' в 'to'; to достаточно большой */
void copy_max(char to[], char from[])
{
    int i;
    i = 0;
    while ((to[i] = from[i]) != '')
        ++i;
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

11.07.2016, 21:02

4

ValeryS

Модератор

Эксперт по электронике

8759 / 6549 / 887

Регистрация: 14.02.2011

Сообщений: 22,972

11.07.2016, 21:09

2

Лучший ответ Сообщение было отмечено Centavrianin как решение

Решение

Цитата
Сообщение от Centavrianin
Посмотреть сообщение

int getline_max(char line[], int MAXLINE);

нельзя так
это объявление функции, а не вызов
после обработки препроцессором макросы развернутся и получишь вот что

C
1
 int getline_max(char line[], int 1000);

напиши как в определении

C
1
int getline_max(char s[], int lim);

или без наименования параметра

C
1
int getline_max(char s[], int );

Добавлено через 16 секунд

Цитата
Сообщение от Centavrianin
Посмотреть сообщение

int getline_max(char line[], int MAXLINE);

нельзя так
это объявление функции, а не вызов
после обработки препроцессором макросы развернутся и получишь вот что

C
1
 int getline_max(char line[], int 1000);

напиши как в определении

C
1
int getline_max(char s[], int lim);

или без наименования параметра

C
1
int getline_max(char s[], int );



3



Даценд

Эксперт .NET

5858 / 4735 / 2940

Регистрация: 20.04.2015

Сообщений: 8,361

11.07.2016, 21:15

3

Centavrianin,
А зачем идентификатор параметра функции совпадает с константой MAXLINE. Объявите

C
1
int getline_max(char s[], int lim);

или

C
1
int getline_max(char[], int);



2



0 / 0 / 0

Регистрация: 11.07.2016

Сообщений: 2

11.07.2016, 22:30

 [ТС]

4

Понял. Спасибо за разъяснение!
Про функции надо будет перечитать еще раз.



0



42 / 10 / 9

Регистрация: 13.03.2015

Сообщений: 74

13.07.2016, 21:35

5

Centavrianin, У меня тоже на этом моменте были проблемы. Помниться я пол дня над ним корпел =)



0



  • Forum
  • Beginners
  • Expected before numeric constant

Expected before numeric constant

Got two errors when compiling my program.

1
2
3
4
5
6
7
8
9
#include "Token.h"
#include <vector>
using namespace std;

class Grid
{
	private:
		vector<vector<Token*> > grid(6,7);
};
1
2
/Users/steve/Desktop/Connect 4/Grid.h:8: error: expected identifier before numeric constant
/Users/steve/Desktop/Connect 4/Grid.h:8: error: expected ',' or '...' before numeric constant

Any suggestions would be greatly appreciated.

Last edited on

1) You cannot call ctors in class definitions like that

2) You cannot create a 2D vector in a single ctor call like that.

To do this you need to write a ctor for Grid, and put the sizing in there:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Grid
{
public:
  Grid()  // default ctor
  {
    // set size of grid
    grid.resize(6);
    for(int i = 0; i < 6; ++i)
      grid[i].resize(7);
  }

private:
  vector< vector<Token*> > grid;
};

You can also do that in a single line using an initializer list

1
2
3
4
5
6
7
class Grid
{
    private:
        vector<vector<Token*> > grid;
    public:
       Grid() : grid ( 6, vector<Token*>(7) ) {}
};

Last edited on

Ah. yeah good call. For whatever reason I didn’t think of that XD

1
2
3
4
5
6
7
{
    // set size of grid
    grid.resize(6);
    for(int i = 0; i < 6; ++i)
      grid[i].resize(7);
  }

Could this be placed in the Grid.cpp file?

Constructors are as all other member functions so you can move their bodies from the header to a source file

Topic archived. No new replies allowed.

Содержание

  1. «error: expected identifier before numeric constant» when using the pre-allocated size constructor for DynamicJsonBuffer #798
  2. Comments
  3. Footer
  4. Ubuntu 18.04: : error: expected identifier or ‘(‘ before numeric constant #159
  5. Comments
  6. Thread: expected identifier before numeric constant
  7. expected identifier before numeric constant
  8. ожидаемый идентификатор или ‘(‘ перед числовой константой?
  9. 4 ответы
  10. ошибка arduino: ожидается ‘,’ или ‘…’ перед числовой константой
  11. Решение
  12. Другие решения

«error: expected identifier before numeric constant» when using the pre-allocated size constructor for DynamicJsonBuffer #798

I am using ArduinoJson for a custom library. I am trying to have a DynamicJsonBuffer as a field of a class, but I am getting the compiler error listed in the title.

header file (test.h):

From this link, it seems as though DynamicJsonBuffer jsonBuffer(size_t) is valid syntax. What is very strange is that by simply having that function call in a setup() of a .ino (NOT in a header file), the error disappears:

I am using ArduinoJson version 5.13.2 for the esp32 WROOM and using ArduinoIDE version 1.8.5.

The text was updated successfully, but these errors were encountered:

This error is not related to ArduinoJson, it’s the syntax for calling the constructor that is not respected.

Indeed, you cannot call the constructor where you declare the member.
Instead, you must call it in the class constructor:

BTW, there are several caveats to using a JsonBuffer as a class member.
In this case, it’s easier to use a DynamicJsonDocument from version 6.

Thanks for your help. Are the «caveats» to using a JsonBuffer as a class member documented anywhere?

I am currently allocating a StaticJsonBuffer on the heap and having a class member point to it. The program runs for a while but then exhibits some strange behavior. Is it possible that manually allocating the StaticJsonBuffer on the heap or having a StaticJsonBuffer* as a class member could cause memory issues?

Unfortunately, switching to DynamicJsonDocuments would take too much time, so I will just try to make work what I have now (if possible).

I don’t think there is a document about that, but you’ll quickly realize that it requires jumping through many hoops. I designed v6 for this use case.

Switching to a JsonDocument should be pretty straightforward; see the guide on arduinojson.org

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Ubuntu 18.04: : error: expected identifier or ‘(‘ before numeric constant #159

When I run «bazel test -c opt . «, I got an error below

e418145f18940c8c0db59ce8308014ec/external/org_gnu_m4/BUILD.bazel:53:10: C++ compilation of rule ‘@org_gnu_m4//:m4’ failed (Exit 1): gcc failed: error executing command

/usr/local/bin/gcc -U_FORTIFY_SOURCE -fstack-protector -Wall -Wunused-but-set-parameter -Wno-free-nonheap-object -fno-omit-frame-pointer -g0 -O2 ‘-D_FORTIFY_SOURCE=1’ -DNDEBUG -ffunction-sections -fdata-sections -MD -MF bazel-out/host/bin/external/org_gnu_m4/objs/m4/binary-io.d ‘-frandom-seed=bazel-out/host/bin/external/org_gnu_m4/objs/m4/binary-io.o’ -D_IO_ftrylockfile ‘-D_IO_IN_BACKUP=0x100’ -D_GNU_SOURCE ‘-DO_BINARY=0’ -iquote external/org_gnu_m4 -iquote bazel-out/host/bin/external/org_gnu_m4 -iquote external/bazel_tools -iquote bazel-out/host/bin/external/bazel_tools -isystem external/org_gnu_m4/lib -isystem bazel-out/host/bin/external/org_gnu_m4/lib -isystem external/org_gnu_m4/build-aux/snippet -isystem bazel-out/host/bin/external/org_gnu_m4/build-aux/snippet -g0 -w -fno-canonical-system-headers -Wno-builtin-macro-redefined ‘-D__DATE=»redacted»‘ ‘-D__TIMESTAMP__=»redacted»‘ ‘-D__TIME__=»redacted»‘ -c external/org_gnu_m4/lib/binary-io.c -o bazel-out/host/bin/external/org_gnu_m4/_objs/m4/binary-io.o)

: error: expected identifier or ‘(‘ before numeric constant.

I appreciate your help!

The text was updated successfully, but these errors were encountered:

Hi KuiWei0004, can you note the output of gcc —version and your distro cat /etc/issue ? We require a sufficiently new GCC since we make use of a bunch of C++17 features and such. Ubuntu 20.04 (which we use for CI) is 9.3.0. We include that Dockerfile (noted in the README) so it’s easy to get started with a known working build environment. Thanks!

Источник

Thread: expected identifier before numeric constant

Thread Tools
Search Thread
Display

expected identifier before numeric constant

I’m getting those errors for the following piece of code

The errors are at nvm_get_production_signature_row_offset.

The definition of the variable is here:

I think I’m seeing over some minor things but I can’t find an answer.

Have used the search here on the forum but found out nothing.

I’ve got the code from ftp://efo-6.ip.peterstar.net/pub/efo. 58977675762dd3 but I can’t find an explanation there to solve the problem

And, the compiler you are using is what??

I still get the same errors

FYI: That is the name of an IDE; NOT the name of a Compiler.

Are you using GNU C or ICC AVR?
If not, the code you posted will NOT work!!

I’m using GNUC, sorry for the miss understanding

I would verify the code is for your chip.
After you verify that I would post on a web-site that supports the chip manufacturer and your C Compiler.

The other option is using GCC to get the preprocessed output (normally option -E) and seeing if that help determine what is missing.
Likely missing an include or using code from wrong micro-controller chip.

Last edited by stahta01; 05-30-2012 at 06:15 AM .

Источник

ожидаемый идентификатор или ‘(‘ перед числовой константой?

У меня есть этот заголовочный файл . по какой-то причине я продолжаю получать сообщение об ошибке log_server.h:48: error: expected identifier or ‘(’ before numeric constant Я получаю эту ошибку в обеих строках, определяющих функции put_evt и print_evt_list, вот как выглядит код:

Я читал, что эта ошибка может быть вызвана тем, что директива предварительной обработки написана более чем в одной строке. но у меня ее нет. Любая идея, что я делаю неправильно?

задан 03 мая ’12, 17:05

Было бы удобно, если бы вы указали строку 48 — Ed Heal

Чтобы исключить какие-то странные макросы/различные странности предварительной обработки, вы должны проверить предварительно обработанный вывод и посмотреть, выглядит ли он нормальным. С участием gcc это можно сделать с помощью -E флаг. — FatalError

Я уже говорил, что ошибка выдается на обеих функциях put_evt и print_evt_list — Varda Elentári

@Кто-то: -E Вариант предлагался пару раз, но попробуем еще раз: что делает команда gcc -E sourcefile.c | grep put_evt сказать? (отрегулируйте любые параметры, которые вам могут понадобиться для добавления gcc работать, например -I ). — Michael Burr

это то, что он говорит . но на самом деле не означает ничего значимого: int put_evt(struct evt *e); int put_evt(struct evt *e) @МайклБерр — Varda Elentári

4 ответы

проблема была в том что у меня struct evt заявлено в другом месте.

ответ дан 10 мая ’12, 22:05

У меня была та же проблема, когда у меня был make-файл с тем же именем, что и у структуры. — викасмк

У меня была та же проблема при вводе перечисления кодов ошибок, которое имело те же идентификаторы, что и идентификаторы из ERRNO. — арнодов

У меня была та же проблема с определением в библиотеке, перезаписывающим определение в другой библиотеке, хотя определение, о котором сообщалось об ошибке, не было перезаписанным. Вместо этого он сообщил об ошибке определения, используемого в перезаписанном определении. Самым простым решением было переместить менее зависимую библиотеку после включения основной библиотеки, чтобы она могла сохранить то же имя, не мешая. — Флабу

Я думаю у тебя есть #define e 2.71828183 или что-то подобное в предыдущих заголовках.

Чтобы узнать наверняка, пропустите код через препроцессор и посмотрите на результат. В gcc это переключатель командной строки -E

Источник

ошибка arduino: ожидается ‘,’ или ‘…’ перед числовой константой

Я новичок в Arduino и C ++ и сталкиваюсь с вышеуказанной ошибкой. Это кажется довольно очевидным, однако я не могу найти пропущенную запятую в коде. Код работал нормально, прежде чем я добавил binaryOut функция, поэтому я верю, что это там.

Было бы хорошо, если бы Arduino дал указание о том, где происходит ошибка.

Любая помощь будет принята с благодарностью.

РЕДАКТИРОВАТЬ: в Arduino HIGH и LOW определены константы (http://arduino.cc/en/Reference/Constants ) и логический тип данных является примитивным (http://en.wikipedia.org/wiki/Primitive_data_type )

EDIT2: я смоделировал binaryOut из примера ( shiftOut ) на изображении ниже.

EDIT3: точная ошибка:

Сначала я думал, что «111» и «112» соответствуют номеру строки, но мой код содержит менее 90 строк.

Решение

Библиотеки Arduino используют идентификаторы dataPin и clockPin для своих собственных целей. Определив их с фактическими значениями в вашем коде, вы сделали код Arduino некомпилируемым. Переименуй их.

Другие решения

Этот ответ только для целей записи.

Ниже строки в примере кода также выдает мне ту же ошибку ожидается ‘,’ или ‘…’ перед числовой константой

Но когда я изменил строки выше, что-то вроде этого (ниже) работает нормально.

при определении вы не можете использовать строчные буквы.

Источник

I am getting this error for the following file. I have no clue why. If any has any idea it would be great.

Error:

resource.h:1:20: error: expected identifier or ‘(‘ before numeric constant

#define IDR_MYMENU 101

^~~

resource.h:1:20: note: in definition of macro ‘IDR_MYMENU’

#define IDR_MYMENU 101

#define IDR_MYMENU 101
#define IDI_MYICON 201
#define ID_FILE_EXIT 9001
#define ID_STUFF_GO 9002

main.c file

#include <windows.h>
#include "resource.h"
#include "res.rc"


const char g_szClassName[] = "myWindowClass";

// Step 4: the Window Procedure
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
        case WM_LBUTTONDOWN:
        {
            char szFileName[MAX_PATH];
            HINSTANCE hInstance = GetModuleHandle(NULL);
            
            GetModuleFileName(hInstance, szFileName, MAX_PATH);
            MessageBox(hwnd, szFileName, "This program is:", MB_OK | MB_ICONINFORMATION);
        }
        break;
        case WM_CLOSE:
        {
            DestroyWindow(hwnd);
        }
        break;
        case WM_DESTROY:
        {
            PostQuitMessage(0);
        }
        break;
        default:
        return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 
                   LPSTR lpCmdLine, int nCmdShow)
{
    WNDCLASSEX wc;
    HWND hwnd;
    MSG Msg;
    
    // Step 1: Registering the window class
    wc.cbSize        = sizeof(WNDCLASSEX);
    wc.style         = 0;
    wc.lpfnWndProc   = WndProc;
    wc.cbClsExtra    = 0;
    wc.cbWndExtra    = 0;
    wc.hInstance     = hInstance;
    wc.hIcon         = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_MYICON));
    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
    wc.lpszMenuName  = MAKEINTRESOURCE(IDR_MYMENU);
    wc.lpszClassName = g_szClassName;
    wc.hIconSm       = (HICON)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_MYICON), IMAGE_ICON, 16, 16, 0);
    
    if(!RegisterClassEx(&wc))
    {
        MessageBox(NULL, "Window Registration Failed!", "Error",
                   MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }
    
    // Step 2: Creating the Window
    hwnd = CreateWindowEx(WS_EX_CLIENTEDGE,
                          g_szClassName,
                          "The title of my window",
                          WS_OVERLAPPEDWINDOW,
                          CW_USEDEFAULT, CW_USEDEFAULT, 240, 120,
                          NULL, NULL, hInstance, NULL);
    
    if(hwnd == NULL)
    {
        MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }
    
    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);
    
    // Step 3: The Message Loop
    while(GetMessage(&Msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }
    return Msg.wParam;
}

res.rc file

#include "resource.h"

IDR_MYMENU MENU
BEGIN
	POPUP "&File"
	BEGIN
		MENUITEM "E&xit", ID_FILE_TEXT
	END

	POPUP "&Stuff"
	BEGIN
		MENUITEM "&Go", ID_STUFF_GO
		MENUITEM "G&o somewhere else", 0, GRAYED
	END
END

IDI_MYICON ICON "menu_one.ico"

Понравилась статья? Поделить с друзьями:
  • Error expected declaration specifiers or before string constant
  • Error expected declaration or statement at end of input перевод
  • Error executing updater binary in zip twrp что делать 4pda
  • Error executing tk17 engine exe
  • Error executing the specified program realtek что делать