I recently got the following error when trying to compile with gcc:
error: missing binary operator before token «(«
Web and SO searches came up with several specific examples of this error, with specific code changes to fix them. But I found no general description of what condition causes this error to be issued.
When and why does gcc emit this error?
asked Jan 24, 2014 at 17:08
0
This is not a compiler error, it is a preprocessor error. It occurs when the preprocessor encounters invalid syntax while trying to evaluate an expression in a #if
or #elif
directive.
One common cause is the sizeof
operator in an #if
directive:
For example:
#define NBITS (sizeof(TYPE)*8)
//later
#if (NBITS>16) //ERROR
This is an error because sizeof
is evaluated by the compiler, not the preprocesor.
Type casts are also not valid preprocessor syntax:
#define ALLBITS ((unsigned int) -1)
//later
#if (ALLBITS>0xFFFF) //ERROR
The rules for what can be in a valid expression are here.
Note also that #if
will evaluate an undefined macro as 0, unless it looks like it takes arguments, in which case you also get this error:
So if THIS
is undefined:
#if THIS == 0 //valid, true
#if THIS > 0 //valid, false
#if THIS() == 0 //invalid. ERROR
Typos in your #if
statement can also cause this message.
answered Jan 24, 2014 at 17:08
AShellyAShelly
34.4k15 gold badges92 silver badges150 bronze badges
3
If you are on Linux, make sure that you do not have a header named features.h
inside your project files.
I had one with this name, which resulted in:
/usr/include/x86_64-linux-gnu/bits/huge_val.h:25: error: function pointer expected
or
/usr/include/bits/huge_val.h:26:18: error: missing binary operator before token
«(«
That is because some system headers like huge_val.h
use macros like __GNUC_PREREQ
that are defined by /usr/include/features.h
(learn more about this header in this SO question).
In my case I first saw this error when I started to use gcc’s -I option which suddenly made gcc select my project include directory before the default system include directories.
answered Nov 30, 2018 at 23:31
1
You get this error sometimes if you have -fno-operator-names
in your compiler flags. I suffered from the exact error while building json
and this solved it.
answered Aug 15, 2019 at 21:03
check the direct. no space,no special
exp:
add_subdirectory(Main)->add_subdirectory(main)
answered Sep 8, 2020 at 9:03
3
PackageManager: Installing tool-pyocd @ ~0.801.0
Downloading...
Unpacking...
tool-pyocd @ 0.801.0 has been successfully installed!
Processing LPC1768 (platform: https://github.com/p3p/pio-nxplpc-arduino-lpc176x/archive/0.1.2.zip; framework: arduino; board: nxp_lpc1768)
--------------------------------------------------------------------------------
Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/nxplpc-arduino-lpc176x/nxp_lpc1768.html
PLATFORM: NXP Arduino LPC176x 0.1.1 > NXP LPC1768
HARDWARE: LPC1768 100MHz, 31.97KB RAM, 464KB Flash
DEBUG: Current (cmsis-dap) On-board (cmsis-dap) External (blackmagic, jlink)
PACKAGES: toolchain-gccarmnoneeabi 1.80201.190214 (8.2.1), framework-arduino-lpc176x 0.2.2
Converting Marlin.ino
LDF: Library Dependency Finder -> http://bit.ly/configure-pio-ldf
LDF Modes: Finder ~ off, Compatibility ~ strict
Found 6 compatible libraries
Scanning dependencies...
Dependency Graph
|-- <Servo> 1.0.0
|-- <LiquidCrystal> 1.0.0
|-- <U8glib-HAL> 0.4.1
|-- <TMCStepper> 0.5.2
|-- <Adafruit NeoPixel> 1.3.0
|-- <SailfishLCD>
Building in debug mode
Unable to find destination disk (Autodetect Error)
Please select it in platformio.ini using the upload_port keyword (https://docs.platformio.org/en/latest/projectconf/section_env_upload.html) or copy the firmware (.pio/build/LPC1768/firmware.bin) manually to the appropriate disk
Compiling .piobuildLPC1768srcsrcHALHAL_LPC1768DebugMonitor.cpp.o
Compiling .piobuildLPC1768srcsrcHALHAL_LPC1768HAL.cpp.o
Compiling .piobuildLPC1768srcsrcHALHAL_LPC1768HAL_SPI.cpp.o
In file included from c:usersdandesktoptempmarlinsrcincMarlinConfigPre.h:54,
from c:usersdandesktoptempmarlinsrcincmarlinconfig.h:28,
from MarlinsrcHALHAL_LPC1768../../core/serial.h:24,
from MarlinsrcHALHAL_LPC1768DebugMonitor.cpp:26:
c:usersdandesktoptempmarlinsrccoredrivers.h:68:51: error: missing binary operator before token "("
#define AXIS_DRIVER_TYPE(A,T) AXIS_DRIVER_TYPE_##A(T)
^
c:usersdandesktoptempmarlinsrccoredrivers.h:91:31: note: in expansion of macro 'AXIS_DRIVER_TYPE'
#define AXIS_IS_TMC(A) ( AXIS_DRIVER_TYPE(A,TMC2130)
^~~~~~~~~~~~~~~~
c:usersdandesktoptempmarlinconfiguration_adv.h:2058:7: note: in expansion of macro 'AXIS_IS_TMC'
#if AXIS_IS_TMC(Z4)
^~~~~~~~~~~
c:usersdandesktoptempmarlinsrccoredrivers.h:68:51: error: missing binary operator before token "("
#define AXIS_DRIVER_TYPE(A,T) AXIS_DRIVER_TYPE_##A(T)
^
c:usersdandesktoptempmarlinsrccoredrivers.h:91:31: note: in expansion of macro 'AXIS_DRIVER_TYPE'
#define AXIS_IS_TMC(A) ( AXIS_DRIVER_TYPE(A,TMC2130)
^~~~~~~~~~~~~~~~
c:usersdandesktoptempmarlinconfiguration_adv.h:2108:7: note: in expansion of macro 'AXIS_IS_TMC'
#if AXIS_IS_TMC(E6)
^~~~~~~~~~~
c:usersdandesktoptempmarlinsrccoredrivers.h:68:51: error: missing binary operator before token "("
#define AXIS_DRIVER_TYPE(A,T) AXIS_DRIVER_TYPE_##A(T)
^
c:usersdandesktoptempmarlinsrccoredrivers.h:91:31: note: in expansion of macro 'AXIS_DRIVER_TYPE'
#define AXIS_IS_TMC(A) ( AXIS_DRIVER_TYPE(A,TMC2130)
^~~~~~~~~~~~~~~~
c:usersdandesktoptempmarlinconfiguration_adv.h:2115:7: note: in expansion of macro 'AXIS_IS_TMC'
#if AXIS_IS_TMC(E7)
^~~~~~~~~~~
Compiling .piobuildLPC1768srcsrcHALHAL_LPC1768MarlinSerial.cpp.o
Compiling .piobuildLPC1768srcsrcHALHAL_LPC1768fast_pwm.cpp.o
In file included from MarlinsrcHALHAL_LPC1768../../inc/MarlinConfigPre.h:54,
from MarlinsrcHALHAL_LPC1768../../inc/MarlinConfig.h:28,
from MarlinsrcHALHAL_LPC1768HAL.cpp:25:
c:usersdandesktoptempmarlinsrccoredrivers.h:68:51: error: missing binary operator before token "("
#define AXIS_DRIVER_TYPE(A,T) AXIS_DRIVER_TYPE_##A(T)
^
c:usersdandesktoptempmarlinsrccoredrivers.h:91:31: note: in expansion of macro 'AXIS_DRIVER_TYPE'
#define AXIS_IS_TMC(A) ( AXIS_DRIVER_TYPE(A,TMC2130)
^~~~~~~~~~~~~~~~
c:usersdandesktoptempmarlinconfiguration_adv.h:2058:7: note: in expansion of macro 'AXIS_IS_TMC'
#if AXIS_IS_TMC(Z4)
^~~~~~~~~~~
c:usersdandesktoptempmarlinsrccoredrivers.h:68:51: error: missing binary operator before token "("
#define AXIS_DRIVER_TYPE(A,T) AXIS_DRIVER_TYPE_##A(T)
^
c:usersdandesktoptempmarlinsrccoredrivers.h:91:31: note: in expansion of macro 'AXIS_DRIVER_TYPE'
#define AXIS_IS_TMC(A) ( AXIS_DRIVER_TYPE(A,TMC2130)
^~~~~~~~~~~~~~~~
c:usersdandesktoptempmarlinconfiguration_adv.h:2108:7: note: in expansion of macro 'AXIS_IS_TMC'
#if AXIS_IS_TMC(E6)
^~~~~~~~~~~
c:usersdandesktoptempmarlinsrccoredrivers.h:68:51: error: missing binary operator before token "("
#define AXIS_DRIVER_TYPE(A,T) AXIS_DRIVER_TYPE_##A(T)
^
c:usersdandesktoptempmarlinsrccoredrivers.h:91:31: note: in expansion of macro 'AXIS_DRIVER_TYPE'
#define AXIS_IS_TMC(A) ( AXIS_DRIVER_TYPE(A,TMC2130)
^~~~~~~~~~~~~~~~
c:usersdandesktoptempmarlinconfiguration_adv.h:2115:7: note: in expansion of macro 'AXIS_IS_TMC'
#if AXIS_IS_TMC(E7)
^~~~~~~~~~~
Compiling .piobuildLPC1768srcsrcHALHAL_LPC1768includedigipot_mcp4451_I2C_routines.c.o
Compiling .piobuildLPC1768srcsrcHALHAL_LPC1768main.cpp.o
In file included from MarlinsrcHALHAL_LPC1768../../inc/MarlinConfigPre.h:54,
from MarlinsrcHALHAL_LPC1768../../inc/MarlinConfig.h:28,
from MarlinsrcHALHAL_LPC1768HAL_SPI.cpp:51:
c:usersdandesktoptempmarlinsrccoredrivers.h:68:51: error: missing binary operator before token "("
#define AXIS_DRIVER_TYPE(A,T) AXIS_DRIVER_TYPE_##A(T)
^
c:usersdandesktoptempmarlinsrccoredrivers.h:91:31: note: in expansion of macro 'AXIS_DRIVER_TYPE'
#define AXIS_IS_TMC(A) ( AXIS_DRIVER_TYPE(A,TMC2130)
^~~~~~~~~~~~~~~~
c:usersdandesktoptempmarlinconfiguration_adv.h:2058:7: note: in expansion of macro 'AXIS_IS_TMC'
#if AXIS_IS_TMC(Z4)
^~~~~~~~~~~
c:usersdandesktoptempmarlinsrccoredrivers.h:68:51: error: missing binary operator before token "("
#define AXIS_DRIVER_TYPE(A,T) AXIS_DRIVER_TYPE_##A(T)
^
c:usersdandesktoptempmarlinsrccoredrivers.h:91:31: note: in expansion of macro 'AXIS_DRIVER_TYPE'
#define AXIS_IS_TMC(A) ( AXIS_DRIVER_TYPE(A,TMC2130)
^~~~~~~~~~~~~~~~
c:usersdandesktoptempmarlinconfiguration_adv.h:2108:7: note: in expansion of macro 'AXIS_IS_TMC'
#if AXIS_IS_TMC(E6)
^~~~~~~~~~~
c:usersdandesktoptempmarlinsrccoredrivers.h:68:51: error: missing binary operator before token "("
#define AXIS_DRIVER_TYPE(A,T) AXIS_DRIVER_TYPE_##A(T)
^
c:usersdandesktoptempmarlinsrccoredrivers.h:91:31: note: in expansion of macro 'AXIS_DRIVER_TYPE'
#define AXIS_IS_TMC(A) ( AXIS_DRIVER_TYPE(A,TMC2130)
^~~~~~~~~~~~~~~~
c:usersdandesktoptempmarlinconfiguration_adv.h:2115:7: note: in expansion of macro 'AXIS_IS_TMC'
#if AXIS_IS_TMC(E7)
^~~~~~~~~~~
In file included from MarlinsrcHALHAL_LPC1768../../inc/MarlinConfigPre.h:54,
from MarlinsrcHALHAL_LPC1768MarlinSerial.cpp:25:
c:usersdandesktoptempmarlinsrccoredrivers.h:68:51: error: missing binary operator before token "("
#define AXIS_DRIVER_TYPE(A,T) AXIS_DRIVER_TYPE_##A(T)
^
c:usersdandesktoptempmarlinsrccoredrivers.h:91:31: note: in expansion of macro 'AXIS_DRIVER_TYPE'
#define AXIS_IS_TMC(A) ( AXIS_DRIVER_TYPE(A,TMC2130)
^~~~~~~~~~~~~~~~
c:usersdandesktoptempmarlinconfiguration_adv.h:2058:7: note: in expansion of macro 'AXIS_IS_TMC'
#if AXIS_IS_TMC(Z4)
^~~~~~~~~~~
c:usersdandesktoptempmarlinsrccoredrivers.h:68:51: error: missing binary operator before token "("
#define AXIS_DRIVER_TYPE(A,T) AXIS_DRIVER_TYPE_##A(T)
^
c:usersdandesktoptempmarlinsrccoredrivers.h:91:31: note: in expansion of macro 'AXIS_DRIVER_TYPE'
#define AXIS_IS_TMC(A) ( AXIS_DRIVER_TYPE(A,TMC2130)
^~~~~~~~~~~~~~~~
c:usersdandesktoptempmarlinconfiguration_adv.h:2108:7: note: in expansion of macro 'AXIS_IS_TMC'
#if AXIS_IS_TMC(E6)
^~~~~~~~~~~
c:usersdandesktoptempmarlinsrccoredrivers.h:68:51: error: missing binary operator before token "("
#define AXIS_DRIVER_TYPE(A,T) AXIS_DRIVER_TYPE_##A(T)
^
c:usersdandesktoptempmarlinsrccoredrivers.h:91:31: note: in expansion of macro 'AXIS_DRIVER_TYPE'
#define AXIS_IS_TMC(A) ( AXIS_DRIVER_TYPE(A,TMC2130)
^~~~~~~~~~~~~~~~
c:usersdandesktoptempmarlinconfiguration_adv.h:2115:7: note: in expansion of macro 'AXIS_IS_TMC'
#if AXIS_IS_TMC(E7)
^~~~~~~~~~~
*** [.piobuildLPC1768srcsrcHALHAL_LPC1768MarlinSerial.cpp.o] Error 1
*** [.piobuildLPC1768srcsrcHALHAL_LPC1768DebugMonitor.cpp.o] Error 1
*** [.piobuildLPC1768srcsrcHALHAL_LPC1768HAL.cpp.o] Error 1
*** [.piobuildLPC1768srcsrcHALHAL_LPC1768HAL_SPI.cpp.o] Error 1
*** [.piobuildLPC1768srcsrcHALHAL_LPC1768persistent_store_flash.cpp.o] Error 1
*** [.piobuildLPC1768srcsrcHALHAL_LPC1768main.cpp.o] Error 1
========================== [FAILED] Took 2.42 seconds ==========================
Environment Status Duration
------------------------------ -------- ------------
megaatmega2560 IGNORED
megaatmega1280 IGNORED
at90usb1286_cdc IGNORED
at90usb1286_dfu IGNORED
DUE IGNORED
DUE_USB IGNORED
DUE_debug IGNORED
LPC1768 FAILED 00:00:02.424
LPC1769 IGNORED
sanguino_atmega644p IGNORED
sanguino_atmega1284p IGNORED
melzi IGNORED
melzi_optiboot IGNORED
rambo IGNORED
STM32F103RE IGNORED
STM32F103RC_fysetc IGNORED
STM32F103RC_bigtree IGNORED
STM32F103RC_bigtree_NOUSB IGNORED
STM32F103RC_bigtree_512K IGNORED
STM32F103RC_bigtree_512K_NOUSB IGNORED
STM32F103RE_bigtree IGNORED
STM32F103RE_bigtree_NOUSB IGNORED
STM32F4 IGNORED
STM32F7 IGNORED
ARMED IGNORED
STM32F103VE_longer IGNORED
mks_robin IGNORED
mks_robin_lite IGNORED
mks_robin_mini IGNORED
mks_robin_nano IGNORED
jgaurora_a5s_a1 IGNORED
STM32F407VE_black IGNORED
BIGTREE_SKR_PRO IGNORED
BIGTREE_BTT002 IGNORED
teensy31 IGNORED
STM32F103CB_malyan IGNORED
chitu_f103 IGNORED
teensy35 IGNORED
esp32 IGNORED
fysetc_f6_13 IGNORED
linux_native IGNORED
SAMD51_grandcentral_m4 IGNORED
include_tree IGNORED
==================== 1 failed, 0 succeeded in 00:00:02.424 ====================
Форум РадиоКот :: Просмотр темы — Проблема макросов в классах.
Автор: | Pink-Pank [ Чт дек 18, 2014 08:42:24 ] |
Заголовок сообщения: | Проблема макросов в классах. |
Всем добрый день! Частенько использую макросы для автоматизированного расчета загружаемых в регистры значений. Например: Код: #define F_CPU 1200000UL OCR0 = LOAD_VALUE; // 8 — предделитель таймера. Режим CTC В общем, если использую подобные макросы при работе с регистрами напрямую или передавая значение функции, то все ОК. И еще. Если я функции класса передаю не переменные, а числовые константы, можно как-то компилятор заставить, чтобы функция не принимала значения через стек (или регистры), а генерировалась инлайном с подстановкой нужных значений, не качая их из стека? Это с учетом того, что она в классе и простой инлайн не катит, но вызывается при этом всего один раз. |
Автор: | ploop [ Чт дек 18, 2014 09:34:27 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
У вас точка с запятой в макросе. Pink-Pank писал(а): Я так предполагаю, что препроцессор сначала подставляет выражение из макроса, а уже потом его рассчитывает Именно так. Pink-Pank писал(а): Если я функции класса передаю не переменные, а числовые константы, можно как-то компилятор заставить, чтобы функция не принимала значения через стек (или регистры), а генерировалась инлайном с подстановкой нужных значений, не качая их из стека? Нет. Функция есть функция, это машинный код в итоге. Препроцессор не сможет запустить её на исполнение в результате компиляции и оставить только результат, так как неизвестно, что там внутри функции вы наворотили. Цитата: то с учетом того, что она в классе и простой инлайн не катит, но вызывается при этом всего один раз. С чего это не может быть инлайновых методов? Вполне могут. |
Автор: | Pink-Pank [ Чт дек 18, 2014 09:54:36 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
В макросе у меня нет точек с запятой. Это я просто здесь «намешал» код и макросы. Щас поправлю. Цитата: С чего это не может быть инлайновых методов? Вполне могут. Не знаю. При попытке оформить метод как инлайн компилятор материться, что функция из класса не может вызываться, как инлайная. Думаю, проблема в области видимости внутренних функций классов или что-то в этом духе.. Ведь если сделать два разных объявления классов с одинаковым набором внутренних переменных, потом создать эти два класса и попытаться присвоить значения одного класса другому, то компиль также выдаст ошибку. Думаю, здесь что-то подобное.. |
Автор: | ploop [ Чт дек 18, 2014 10:10:36 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
Думаю, вы что-то намутили… Pink-Pank писал(а): Ведь если сделать два разных объявления классов с одинаковым набором внутренних переменных, потом создать эти два класса и попытаться присвоить значения одного класса другому, то компиль также выдаст ошибку. Думаю, здесь что-то подобное.. Как вы это делаете? Ничего не понял, покажите пример. |
Автор: | Pink-Pank [ Чт дек 18, 2014 10:17:32 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
Методы.. Шметоды.. Это все условности! ))) Главное — полет мысли! )))))) Код: class First { class Second { class First obj1; Да и как я мог намутить, если передача обычного числа, макроса или переменной прокатывает, а макрос с преобразованием типов вызывает ошибку? |
Автор: | ploop [ Чт дек 18, 2014 10:46:29 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
Pink-Pank писал(а): // ошибка: obj1 и obj2 имеют разные типы Естественно! Первый имеет тип First, второй — Second. А если они внутри одинаковы — так это ваша проблема, так как такой подход рвёт все шаблоны ООП. Pink-Pank писал(а): А если выражение (uint16_t)((double)F_CPU/16), то получается облом… Ошибка то хоть какая? |
Автор: | Pink-Pank [ Чт дек 18, 2014 10:52:31 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
я ж писал |
Автор: | Siarzhuk [ Чт дек 18, 2014 11:28:52 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
Pink-Pank писал(а): А вот если в макросе есть приведение типа переменной, то компилятор начинает материться, что: С какой проблемой? Где кот с классами? Телепатам гадать не на чем. При непонятных проблемах с макросами нужно включать опцию -F Preprocess only результат работы препроцессора будет сохранен в файле с расширением *.i а компиляция не будет производиться. При нормальной компиляции этот вот *.i и скармливается компилятору. Обычно достаточно одного взгляда на развёрнутый макрос чтобы понять в чём проблема. Для inline попробуйте определить тело функции прямо v определении класса в h файле. А вообще нужно читать мануал на компилятор соответствующую тему — там наверняка оговариваются нюансы использования. Pink-Pank писал(а): Да и как я мог намутить, Мутят все, мутили и будут мутить всегда и вовеки — чем вы лучше других? Как и во всяком ремесле опыт решает — другие просто эти шишки уже собрали на свои головы пока вы прохлаждались — вот и всё. Pink-Pank писал(а): // ошибка: obj1 и obj2 имеют разные типы Определите операторы присваивания и будет вам счастье. Это нужно делать даже для одинаковых типов если они имеют ссылки на внешние ресурсы — по умолчанию компилятор создает оператор присваивания с простым копированием данных если оператор=(…) для этого типа не задан прокладкой между стулом и клавиатурой. |
Автор: | Pink-Pank [ Чт дек 18, 2014 11:51:51 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
Цитата: Для inline попробуйте определить тело функции прямо v определении класса в h файле. А вообще нужно читать мануал на компилятор соответствующую тему — там наверняка оговариваются нюансы использования. Уже пробовал.. Не помогает.. Цитата: С какой проблемой? Где кот с классами? Да что Вам мой кот, если компилятор глотает обычные числовые значения и макросы без преобразования типов. Цитата: Определите операторы присваивания и будет вам счастье. поподробнее можно? Что-то я не очень понял, о чем Вы? Вы про перегрузку операторов? Цитата: -F Preprocess only не -F, а -E |
Автор: | Siarzhuk [ Чт дек 18, 2014 12:13:54 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
Pink-Pank писал(а): Цитата: С какой проблемой? Где кот с классами? Да что Вам мой кот, если компилятор глотает обычные числовые значения и макросы без преобразования типов. А без кота разговор беспредметен. Ну глотает, и чо? А вот нужные вам макросы не глотает. Не переваривает стало-быть их. Несъедобно готовите раз котейко давится. Скобок туда по уму добавьте — сожрёць как миленький — и не такое сжирал. И ещё раз про *.i выхлоп напоминаю — дюже важный доку́мент для пущего понимания процессов «прокладкой». |
Автор: | Siarzhuk [ Чт дек 18, 2014 12:22:04 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
Pink-Pank писал(а): Вы про перегрузку операторов? да, они, что-то типа Код: Second* Second::operator=(const First& first) { Pink-Pank писал(а): Цитата: -F Preprocess only не -F, а -E Ну может и не -F и не *.i — вам на месте виднее — гляньте в папках где временные файлы/результаты компиляции — может какие *.pre или что-то в этом роде сохраняется — а сообщение означает что линкер не нашёл чего хотел — т.е. как-бы понятно почему — объектников-то ведь нету — один препроцессор. удачи. |
Автор: | Pink-Pank [ Чт дек 18, 2014 12:25:57 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
Цитата: Несъедобно готовите раз котейко давится. Скобок туда по уму добавьте — сожрёць как миленький — и не такое сжирал. Видно, скобочками и давится — потому что у меня их как раз валом! А как Вам тот факт, что тот же макрос обычной функцией принимается без проблем? Вот Вам мой класс *.h Вот мой класс *.cpp Вот моя функция с вызовом и подстановкой макроса: |
Автор: | Siarzhuk [ Чт дек 18, 2014 12:36:37 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
Pink-Pank писал(а): Цитата: Несъедобно готовите раз котейко давится. Скобок туда по уму добавьте — сожрёць как миленький — и не такое сжирал. Видно, как раз скобочками и давится — потому что у меня их как раз валом! А как Вам тот факт, что тот же макрос обычной функцией принимается без проблем? Ничего удивительного — даже если макрос не огорожен скобками — результат исчисления по любому уйдёт в функцию, а вот неогороженный макрос в выражении имеет все шансы быть растащенным в стороны операциями с более высоким приоритетом. Типовая ошибка — потому в любом букваре по сишному препроцессору есть соответствующие примеры и страшилки. |
Автор: | ploop [ Чт дек 18, 2014 14:02:46 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
У вас проблема точно в макросе? Раз ругается на битовую операцию, значит может быть в структуре Work_regim_Def, что после него идёт? Вы кажется намутили с областью видимости индентификатора UART |
Автор: | Pink-Pank [ Чт дек 18, 2014 14:42:32 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
то, что идет после никакого отношения к ошибке не имеет. Я те параметры пробовал и вовсе комментировать, оставлял только один, который не робит. Не помогло. Перечисления я там сделал, чтобы вводимые значения в качестве параметров были фиксированными. Чтобы пользователь класса не мог запулить туда что-то не удобоваримое. Да и при нажатии на ошибку выкидывает именно на макрос. Попробую в IAR загнать.. если схавает — значит студия ка-ка. Если нет и с такой же ошибкой — значит ка-ка я! |
Автор: | Siarzhuk [ Чт дек 18, 2014 17:07:33 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
Pink-Pank писал(а): А функция round точно видна и не перекрывается переменной с таким именем? Да и %s/BOAD/BAUD/g надо бы сделать. |
Автор: | Pink-Pank [ Пт дек 19, 2014 07:33:56 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
Видна. У меня нет таких переменных. |
Автор: | Аlex [ Пт дек 19, 2014 07:57:40 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
А если её (round) для пробы выкинуть из макроса, проглотит ? |
Автор: | Siarzhuk [ Пт дек 19, 2014 10:55:49 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
Pink-Pank писал(а): Видна. У меня нет таких переменных. Т.е. если написать пару строками раньше что-то типа double d = round(2342.346456); компилятор скушает и не ругнётся? ну разбивайте макрос по операциям на разных строчках с промежуточными результатами и смотрите на какой чертыхнётся если лень выхлоп препроцессора искать и времени не жалко. В порядке постукивания по бубну оберните всю подстановку в скобки. Или воспользуйтесь конструкторо-подобной нотацией оператора приведения: Код: #define UBRR uint16_t( round( double(F_CPU) / 16.0 / BOAD_RATE ) — 1) |
Автор: | BCluster [ Пт дек 19, 2014 12:37:19 ] |
Заголовок сообщения: | Re: Проблема макросов в классах. |
Проверил в IAR ARM такую конструкцию, она работает |
Страница 1 из 2 | Часовой пояс: UTC + 3 часа |
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group http://www.phpbb.com/ |
Подскажите взял конфинги, поместил в марлин немного подредактировал а он не хочет компилироваться.
Моя прошивка
пишет
Processing LPC1768 (board: nxp_lpc1768; platform: https://github.com/p3p/pio-nxplpc-arduino-lpc176x/archive/0.1.3.zip; framework: arduino)
—————————————————————————————————————————————————Verbose mode can be enabled via `-v, —verbose` option
In file included from a:marlinmarlin 2022marlinsrcincMarlinConfigPre.h:39,
from a:marlinmarlin 2022marlinsrcincmarlinconfig.h:28,
from buildroot/share/PlatformIO/scripts/common-dependencies.h:29:
a:marlinmarlin 2022marlinconfiguration.h:23:2: error: #error «Don’t build with import-2.0.x configurations!»
23 | #error «Don’t build with import-2.0.x configurations!»
| ^~~~~
a:marlinmarlin 2022marlinconfiguration.h:24:2: error: #error «Use the ‘bugfix…’ or ‘release…’ configurations matching your Marlin version.»
24 | #error «Use the ‘bugfix…’ or ‘release…’ configurations matching your Marlin version.»
| ^~~~~
In file included from a:marlinmarlin 2022marlinsrcincMarlinConfigPre.h:55,
from a:marlinmarlin 2022marlinsrcincmarlinconfig.h:28,
from buildroot/share/PlatformIO/scripts/common-dependencies.h:29:
a:marlinmarlin 2022marlinsrccoredrivers.h:83:51: error: missing binary operator before token «(»
83 | #define AXIS_DRIVER_TYPE(A,T) AXIS_DRIVER_TYPE_##A(T)
| ^
a:marlinmarlin 2022marlinsrccoredrivers.h:123:31: note: in expansion of macro ‘AXIS_DRIVER_TYPE’
123 | #define AXIS_IS_TMC(A) ( AXIS_DRIVER_TYPE(A,TMC2130) || AXIS_DRIVER_TYPE(A,TMC2160)
| ^~~~~~~~~~~~~~~~
a:marlinmarlin 2022marlinconfiguration_adv.h:2879:7: note: in expansion of macro ‘AXIS_IS_TMC’
2879 | #if AXIS_IS_TMC(U)
| ^~~~~~~~~~~
a:marlinmarlin 2022marlinsrccoredrivers.h:83:51: error: missing binary operator before token «(»
83 | #define AXIS_DRIVER_TYPE(A,T) AXIS_DRIVER_TYPE_##A(T)
| ^
a:marlinmarlin 2022marlinsrccoredrivers.h:123:31: note: in expansion of macro ‘AXIS_DRIVER_TYPE’
123 | #define AXIS_IS_TMC(A) ( AXIS_DRIVER_TYPE(A,TMC2130) || AXIS_DRIVER_TYPE(A,TMC2160)
| ^~~~~~~~~~~~~~~~
a:marlinmarlin 2022marlinconfiguration_adv.h:2889:7: note: in expansion of macro ‘AXIS_IS_TMC’
2889 | #if AXIS_IS_TMC(V)
| ^~~~~~~~~~~
a:marlinmarlin 2022marlinsrccoredrivers.h:83:51: error: missing binary operator before token «(»
83 | #define AXIS_DRIVER_TYPE(A,T) AXIS_DRIVER_TYPE_##A(T)
| ^
a:marlinmarlin 2022marlinsrccoredrivers.h:123:31: note: in expansion of macro ‘AXIS_DRIVER_TYPE’
123 | #define AXIS_IS_TMC(A) ( AXIS_DRIVER_TYPE(A,TMC2130) || AXIS_DRIVER_TYPE(A,TMC2160)
| ^~~~~~~~~~~~~~~~
a:marlinmarlin 2022marlinconfiguration_adv.h:2899:7: note: in expansion of macro ‘AXIS_IS_TMC’
2899 | #if AXIS_IS_TMC(W)
| ^~~~~~~~~~~
CalledProcessError: Command ‘»C:UsersUser.platformiopackagestoolchain-gccarmnoneeabibinarm-none-eabi-g++.exe» -D__MARLIN_FIRMWARE__ -DNDEBUG -DU8G_HAL_LINKS -D__MARLIN_DEPS__ -w -dM -E -x c++ buildroot/share/PlatformIO/scripts/common-dependencies.h’ returned non-zero exit status 1.:
File «C:UsersUser.platformiopenvlibsite-packagesplatformiobuildermain.py», line 179:
env.SConscript(item, exports=»env»)
File «C:UsersUser.platformiopackagestool-sconsscons-local-4.3.0SConsScriptSConscript.py», line 597:
return _SConscript(self.fs, *files, **subst_kw)
File «C:UsersUser.platformiopackagestool-sconsscons-local-4.3.0SConsScriptSConscript.py», line 285:
exec(compile(scriptdata, scriptname, ‘exec’), call_stack[-1].globals)
File «A:marlinMarlin 2022buildrootsharePlatformIOscriptscommon-dependencies.py», line 247:
apply_features_config()
File «A:marlinMarlin 2022buildrootsharePlatformIOscriptscommon-dependencies.py», line 133:
if not env.MarlinFeatureIsEnabled(feature):
File «C:UsersUser.platformiopackagestool-sconsscons-local-4.3.0SConsUtil.py», line 742:
return self.method(*nargs, **kwargs)
File «A:marlinMarlin 2022buildrootsharePlatformIOscriptscommon-dependencies.py», line 216:
load_marlin_features()
File «A:marlinMarlin 2022buildrootsharePlatformIOscriptscommon-dependencies.py», line 204:
define_list = run_preprocessor(env)
File «A:marlinMarlin 2022buildrootsharePlatformIOscriptspreprocessor.py», line 42:
define_list = subprocess.check_output(cmd, shell=True).splitlines()
File «C:UsersUser.platformiopython3libsubprocess.py», line 424:
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File «C:UsersUser.platformiopython3libsubprocess.py», line 528:
raise CalledProcessError(retcode, process.args,
=========================================================== [FAILED] Took 1.54 seconds ===========================================================
Alt-title: a series of unfortunate events.
Hello, I’m new here, please be gentle with the programming vernacular.
Info:
Linux, ubuntu 18.04
Qt version 5.13.0
now: Qt-5.12.0
Qt creator version: 4.9.3(not sure, uninstalled this)
now: Qt creator version 4.8.0
Qmake 3.1
Basically, I wrote a program using qt creator. The kit I used was autodetected: «Desktop Qt 5.13.0 GCC 64bit»
On trying to release my program, I searched for ways to convert it into an appimage. I came across «linuxdeployqt». However, linuxdeployqt could not find Qt-5.13.0. I will not go into detail, but I decided to port my program to Qt5.12.0.
I downloaded 5.12.0’s online installer. After installing, the auto-detected kit «Desktop Qt 5.12.0 GCC 64bit» popped up in my kit manager. So I reconfigured my project to run on that kit, and I was met with 700+ error messages, of which a large portion were ‘Missing binary operator before token «(«‘
https://forum.qt.io/topic/27925/solved-qt_deprecated_since-gives-error-missing-binary-operator-before-token-in-qnamespace-h
This forum does not help me, because I tried starting a new project in qt creator:
file->new file/project->application->qt quick application — empty
And the same issue occured. The problem identified in the forum was that a header file name conflicted with some other system stuff. This would be impossible on a fresh project with nothing in it(and no header files, for that matter)
https://stackoverflow.com/questions/21338385/what-does-the-compiler-error-missing-binary-operator-before-token-mean
This doesn’t help me either. Something to do with incorrect syntax in preprocessor commands. Doesn’t help me, I’ve never even touched that stuff.
I tried uninstalling qt5.13 and 5.12 using the maintenance tool for each. Upon reinstalling qt5.12 using the online installer, and starting a fresh project, the same error occurs.
I checked my kit manager, and confirmed that the kit was using qmake located in my installed qt5.12.0/5.12.0/lib/ folder.
I don’t really know whats going wrong, I’m guessing it isn’t related to my own program, since fresh projects have the same problem. Any help appreciated
Fresh project I created to test:
«qt12test»
-qt12test.pro
-qt12test.pro.user
-main.cpp
-main.qml
-qml.qrc
Error message I got from running this fresh project using Qt5.12.0 kit:
In file included from /usr/include/features.h:365:0,
from /usr/include/x86_64-linux-gnu/c++/7/bits/os_defines.h:39,
from /usr/include/x86_64-linux-gnu/c++/7/bits/c++config.h:533,
from /usr/include/c++/7/type_traits:38,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qglobal.h:45,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qatomic.h:41,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qrefcount.h:43,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qbytearray.h:44,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qurl.h:44,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtQml/qqmlengine.h:43,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtQml/qqmlapplicationengine.h:43,
from ../qt12test/main.cpp:1:
/usr/include/x86_64-linux-gnu/sys/cdefs.h:467:49: error: missing binary operator before token "("
#if __GNUC_PREREQ (4,8) || __glibc_clang_prereq (3,5)
^
In file included from /usr/include/c++/7/cstdlib:75:0,
from /usr/include/c++/7/bits/stl_algo.h:59,
from /usr/include/c++/7/algorithm:62,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qglobal.h:142,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qatomic.h:41,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qrefcount.h:43,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qbytearray.h:44,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qurl.h:44,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtQml/qqmlengine.h:43,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtQml/qqmlapplicationengine.h:43,
from ../qt12test/main.cpp:1:
/usr/include/stdlib.h:133:35: error: missing binary operator before token "("
#if __HAVE_FLOAT16 && __GLIBC_USE (IEC_60559_TYPES_EXT)
^
/usr/include/stdlib.h:139:35: error: missing binary operator before token "("
#if __HAVE_FLOAT32 && __GLIBC_USE (IEC_60559_TYPES_EXT)
^
/usr/include/stdlib.h:145:35: error: missing binary operator before token "("
#if __HAVE_FLOAT64 && __GLIBC_USE (IEC_60559_TYPES_EXT)
^
/usr/include/stdlib.h:151:36: error: missing binary operator before token "("
#if __HAVE_FLOAT128 && __GLIBC_USE (IEC_60559_TYPES_EXT)
^
/usr/include/stdlib.h:157:36: error: missing binary operator before token "("
#if __HAVE_FLOAT32X && __GLIBC_USE (IEC_60559_TYPES_EXT)
^
/usr/include/stdlib.h:163:36: error: missing binary operator before token "("
#if __HAVE_FLOAT64X && __GLIBC_USE (IEC_60559_TYPES_EXT)
^
/usr/include/stdlib.h:169:37: error: missing binary operator before token "("
#if __HAVE_FLOAT128X && __GLIBC_USE (IEC_60559_TYPES_EXT)
^
/usr/include/stdlib.h:211:17: error: missing binary operator before token "("
#if __GLIBC_USE (IEC_60559_BFP_EXT)
^
/usr/include/stdlib.h:225:35: error: missing binary operator before token "("
#if __HAVE_FLOAT16 && __GLIBC_USE (IEC_60559_TYPES_EXT)
^
/usr/include/stdlib.h:231:35: error: missing binary operator before token "("
#if __HAVE_FLOAT32 && __GLIBC_USE (IEC_60559_TYPES_EXT)
^
/usr/include/stdlib.h:237:35: error: missing binary operator before token "("
#if __HAVE_FLOAT64 && __GLIBC_USE (IEC_60559_TYPES_EXT)
^
/usr/include/stdlib.h:243:36: error: missing binary operator before token "("
#if __HAVE_FLOAT128 && __GLIBC_USE (IEC_60559_TYPES_EXT)
^
/usr/include/stdlib.h:249:36: error: missing binary operator before token "("
#if __HAVE_FLOAT32X && __GLIBC_USE (IEC_60559_TYPES_EXT)
^
/usr/include/stdlib.h:255:36: error: missing binary operator before token "("
#if __HAVE_FLOAT64X && __GLIBC_USE (IEC_60559_TYPES_EXT)
^
/usr/include/stdlib.h:261:37: error: missing binary operator before token "("
#if __HAVE_FLOAT128X && __GLIBC_USE (IEC_60559_TYPES_EXT)
^
In file included from /usr/lib/gcc/x86_64-linux-gnu/7/include/stdint.h:9:0,
from /usr/include/c++/7/bits/atomic_base.h:36,
from /usr/include/c++/7/atomic:41,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qatomic_cxx11.h:45,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qbasicatomic.h:53,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qatomic.h:46,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qglobal.h:1204,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qatomic.h:41,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qrefcount.h:43,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qbytearray.h:44,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qurl.h:44,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtQml/qqmlengine.h:43,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtQml/qqmlapplicationengine.h:43,
from ../qt12test/main.cpp:1:
/usr/include/stdint.h:286:17: error: missing binary operator before token "("
#if __GLIBC_USE (IEC_60559_BFP_EXT)
^
In file included from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qarraydata.h:44:0,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qbytearray.h:46,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qurl.h:44,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtQml/qqmlengine.h:43,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtQml/qqmlapplicationengine.h:43,
from ../qt12test/main.cpp:1:
/usr/include/string.h:164:21: error: missing binary operator before token "("
|| __GLIBC_USE (LIB_EXT2))
^
/usr/include/string.h:173:43: error: missing binary operator before token "("
#if defined __USE_XOPEN2K8 || __GLIBC_USE (LIB_EXT2)
^
In file included from /usr/include/c++/7/cwchar:44:0,
from /usr/include/c++/7/bits/postypes.h:40,
from /usr/include/c++/7/bits/char_traits.h:40,
from /usr/include/c++/7/string:40,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qbytearray.h:52,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qurl.h:44,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtQml/qqmlengine.h:43,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtQml/qqmlapplicationengine.h:43,
from ../qt12test/main.cpp:1:
/usr/include/wchar.h:564:43: error: missing binary operator before token "("
#if defined __USE_XOPEN2K8 || __GLIBC_USE (LIB_EXT2)
^
In file included from /usr/include/c++/7/cstdio:42:0,
from /usr/include/c++/7/ext/string_conversions.h:43,
from /usr/include/c++/7/bits/basic_string.h:6361,
from /usr/include/c++/7/string:52,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qbytearray.h:52,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qurl.h:44,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtQml/qqmlengine.h:43,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtQml/qqmlapplicationengine.h:43,
from ../qt12test/main.cpp:1:
/usr/include/stdio.h:276:43: error: missing binary operator before token "("
#if defined __USE_XOPEN2K8 || __GLIBC_USE (LIB_EXT2)
^
/usr/include/stdio.h:349:17: error: missing binary operator before token "("
#if __GLIBC_USE (LIB_EXT2)
^
/usr/include/stdio.h:567:17: error: missing binary operator before token "("
#if __GLIBC_USE (DEPRECATED_GETS)
^
/usr/include/stdio.h:592:43: error: missing binary operator before token "("
#if defined __USE_XOPEN2K8 || __GLIBC_USE (LIB_EXT2)
^
In file included from /usr/include/c++/7/ext/string_conversions.h:43:0,
from /usr/include/c++/7/bits/basic_string.h:6361,
from /usr/include/c++/7/string:52,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qbytearray.h:52,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtCore/qurl.h:44,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtQml/qqmlengine.h:43,
from ../../Qt5.12.0/5.12.0/gcc_64/include/QtQml/qqmlapplicationengine.h:43,
from ../qt12test/main.cpp:1:
/usr/include/c++/7/cstdio:124:11: error: ‘::gets’ has not been declared
using ::gets;
^~~~
Makefile:816: recipe for target 'main.o' failed
make: *** [main.o] Error 1
12:06:13: The process "/usr/bin/make" exited with code 2.
Error while building/deploying project qt12test (kit: Desktop Qt 5.12.0 GCC 64bit)
When executing step "Make"
I tried upgrade to Ubuntu 18.04 and compile a simple C program from the terminal with gcc -o test test.c
.
#include <stdio.h>
void main() {
printf("hn");
}
but it threw a missing binary operator before token "("
error.
in file included from /usr/local/include/features.h:375:0
from /usr/include/x86_64-linux-gnu/bits/libc-header-start.h:33
from /usr/include/stdio.h:27
from test.c:1
/usr/include/x86_64-linux-gnu/sys/cdef.h:467:79: error :missing binary operator before token "("
#if __GNUC_PREREQ (4,8) || __glibc_clang_prereq (3,5)
In file included from test.c:1:0:
/usr/include/stdio.h:276:43: error: missing binary operator before token "("
#if defined __USE_XOPEN2K8 || __GLIBC_USE (LIB (LIB_EXT2)
gcc version 7.5.0
karel
107k93 gold badges263 silver badges290 bronze badges
asked Apr 26, 2020 at 19:15
2
The current default version of gcc for 18.04 is 7.4, not 7.5. Run find /usr/include/ -name "stdio.h"
. The results should include /usr/include/stdio.h
and be similar but not necessarily identical to this:
$ find /usr/include/ -name "stdio.h" /usr/include/bsd/stdio.h /usr/include/x86_64-linux-gnu/bits/stdio.h /usr/include/stdio.h /usr/include/c++/7/tr1/stdio.h /usr/include/c++/8/tr1/stdio.h
If no results are returned run the following command:
sudo apt install --reinstall gcc build-essential
answered Apr 27, 2020 at 13:31
karelkarel
107k93 gold badges263 silver badges290 bronze badges
1
- Forum
- General Programming Boards
- C Programming
- Error: missing binary operator before token «(«
-
08-02-2013
#1
Registered User
Error: missing binary operator before token «(»
Hi,
I have a problem with #if in preprocesor (
gcc-4.8.1).
Such program works fine:
Code:
#include <stdio.h> #define NUMB1 8000000UL #define NUMB2 64 #define RESULT (int)((1778E-6 * NUMB1 / NUMB2 * 0.85)+0.5) int main(void) { printf("%d",RESULT); return 0; }
the RESULT has correct value 189.
But when I want define warning reaction of value of RESULT like this:
Code:
#if RESULT > 100 # warning "Some text ...." #endif
the compiler does not compile the program:
Code:
#include <stdio.h> #define NUMB1 8000000UL #define NUMB2 64 #define RESULT (int)((1778E-6 * NUMB1 / NUMB2 * 0.85)+0.5) #if RESULT > 100 # warning "Some text ...." #endif int main(void) { printf("%d",RESULT); return 0; }
errors:
Code:
prog.c:6:21: error: missing binary operator before token "(" #define RESULT (int)((1778E-6 * NUMB1 / NUMB2 * 0.85)+0.5) ^ prog.c:8:5: note: in expansion of macro ‘RESULT’ #if RESULT > 100 ^
What am I doing wrong?
Last edited by JakubST; 08-02-2013 at 02:33 PM.
-
08-02-2013
#2
Registered User
Code:
#define RESULT (int)((1778E-6 * NUMB1 / NUMB2 * 0.85)+0.5)
try this instead
Code:
#define RESULT ((1778E-6 * NUMB1 / NUMB2 * 0.85)+0.5)
Likely the prepossessing does NOT support cast to int.
Tim S.
«…a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match..» Bill Bryson
-
08-02-2013
#3
Registered User
Code:
#include <stdio.h> #define NUMB1 8000000UL #define NUMB2 64 #define RESULT ((1778E-6 * NUMB1 / NUMB2 * 0.85)+0.5) #if RESULT > 100 # warning "Some text ...." #endif int main(void) { printf("%12.6f",RESULT); return 0; }
Errors:
Code:
prog.c:6:18: error: floating constant in preprocessor expression #define RESULT ((1778E-6 * NUMB1 / NUMB2 * 0.85)+0.5) ^ prog.c:8:5: note: in expansion of macro �RESULT� #if RESULT > 100 ^ prog.c:6:44: error: floating constant in preprocessor expression #define RESULT ((1778E-6 * NUMB1 / NUMB2 * 0.85)+0.5) ^ prog.c:8:5: note: in expansion of macro �RESULT� #if RESULT > 100 ^ prog.c:6:50: error: floating constant in preprocessor expression #define RESULT ((1778E-6 * NUMB1 / NUMB2 * 0.85)+0.5) ^ prog.c:8:5: note: in expansion of macro �RESULT� #if RESULT > 100 ^
-
08-02-2013
#4
Registered User
error: floating constant in preprocessor expression
Seems pretty clear, you can’t use floating point constants in your pre-processor expressions. Sounds like your preprocessor isn’t able to do floating point calculations to evaluate that expression and compare it to emit the conditional warning. You don’t say which compiler you’re using, but if it’s GCC, you’re out of luck: The C Preprocessor: Conditionals. I can’t find anything in the standard that requires the implementation to either support or explicitly not support floats in preprocessor directives, so I don’t know how universal this behavior is.
Considering NUMB1 and NUMB2 are known ahead of time, you should know the value of result and thus whether the warning will be emitted. Perhaps precompute the value and #define your macro as a single constant instead of an expression. Don’t even use a #if to check if the result > 100, you will know.
-
08-02-2013
#5
Registered User
-
08-02-2013
#6
Registered User
Originally Posted by anduril462
I can’t find anything in the standard that requires the implementation to either support or explicitly not support floats in preprocessor directives, so I don’t know how universal this behavior is.
You need to read carefully (because it is not said outright, so it is necessary to track through the specification of a number of elements of syntax) but it is in the standard.
Even if it wasn’t standard, the results of all floating point operations are — strictly speaking, due to limited precision and accuracy — implementation defined. Enough programmers get confused by the fact that 0.1 and 1.0/10.0 are not necessarily equal. Imagine the confusion if that uncertainty affected the preprocessor (which can completely change the behaviour of a program).
Right 98% of the time, and don’t care about the other 3%.
If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.
-
08-02-2013
#7
and the hat of int overfl
Popular pages
- Exactly how to get started with C++ (or C) today
- C Tutorial
- C++ Tutorial
- 5 ways you can learn to program faster
- The 5 Most Common Problems New Programmers Face
- How to set up a compiler
- 8 Common programming Mistakes
- What is C++11?
- Creating a game, from start to finish
Recent additions
- How to create a shared library on Linux with GCC — December 30, 2011
- Enum classes and nullptr in C++11 — November 27, 2011
- Learn about The Hash Table — November 20, 2011
- Rvalue References and Move Semantics in C++11 — November 13, 2011
- C and C++ for Java Programmers — November 5, 2011
- A Gentle Introduction to C++ IO Streams — October 10, 2011
Similar Threads
-
Replies: 3
Last Post: 08-21-2012, 11:50 PM
-
Replies: 10
Last Post: 08-09-2012, 12:48 PM
-
Replies: 9
Last Post: 07-27-2011, 08:39 PM
-
Replies: 9
Last Post: 03-31-2009, 04:23 PM
-
Replies: 2
Last Post: 06-29-2007, 07:55 AM
When installing ZoneMinder 1.25.0 in CentOS 6.4 (64-bit) the following error pops up when executing make
:
zm_ffmpeg_camera.cpp:105:44: error: missing binary operator before token «(«
Full log:
zm_ffmpeg_camera.cpp:105:44: error: missing binary operator before token "("
In file included from zm_ffmpeg_camera.cpp:24:
zm_ffmpeg_camera.h:39: error: ISO C++ forbids declaration of ‘AVFormatContext’ with no type
zm_ffmpeg_camera.h:39: error: expected ‘;’ before ‘*’ token
zm_ffmpeg_camera.h:41: error: ISO C++ forbids declaration of ‘AVCodecContext’ with no type
zm_ffmpeg_camera.h:41: error: expected ‘;’ before ‘*’ token
zm_ffmpeg_camera.h:42: error: ISO C++ forbids declaration of ‘AVCodec’ with no type
zm_ffmpeg_camera.h:42: error: expected ‘;’ before ‘*’ token
zm_ffmpeg_camera.h:44: error: ISO C++ forbids declaration of ‘AVFrame’ with no type
zm_ffmpeg_camera.h:44: error: expected ‘;’ before ‘*’ token
zm_ffmpeg_camera.h:45: error: ISO C++ forbids declaration of ‘AVFrame’ with no type
zm_ffmpeg_camera.h:45: error: expected ‘;’ before ‘*’ token
zm_ffmpeg_camera.cpp: In constructor ‘FfmpegCamera::FfmpegCamera(int, const std::string&, int, int, int, int, int, int, int, bool)’:
zm_ffmpeg_camera.cpp:35: error: ‘mFormatContext’ was not declared in this scope
zm_ffmpeg_camera.cpp:37: error: ‘mCodecContext’ was not declared in this scope
zm_ffmpeg_camera.cpp:38: error: ‘mCodec’ was not declared in this scope
zm_ffmpeg_camera.cpp:40: error: ‘mRawFrame’ was not declared in this scope
zm_ffmpeg_camera.cpp:41: error: ‘mFrame’ was not declared in this scope
zm_ffmpeg_camera.cpp: In destructor ‘virtual FfmpegCamera::~FfmpegCamera()’:
zm_ffmpeg_camera.cpp:46: error: ‘mFrame’ was not declared in this scope
zm_ffmpeg_camera.cpp:46: error: ‘av_freep’ was not declared in this scope
zm_ffmpeg_camera.cpp:47: error: ‘mRawFrame’ was not declared in this scope
zm_ffmpeg_camera.cpp:51: error: ‘sws_freeContext’ was not declared in this scope
zm_ffmpeg_camera.cpp:54: error: ‘mCodecContext’ was not declared in this scope
zm_ffmpeg_camera.cpp:56: error: ‘avcodec_close’ was not declared in this scope
zm_ffmpeg_camera.cpp:59: error: ‘mFormatContext’ was not declared in this scope
zm_ffmpeg_camera.cpp:61: error: ‘av_close_input_file’ was not declared in this scope
zm_ffmpeg_camera.cpp: In member function ‘void FfmpegCamera::Initialise()’:
zm_ffmpeg_camera.cpp:78: error: ‘AV_LOG_DEBUG’ was not declared in this scope
zm_ffmpeg_camera.cpp:78: error: ‘av_log_set_level’ was not declared in this scope
zm_ffmpeg_camera.cpp:80: error: ‘AV_LOG_QUIET’ was not declared in this scope
zm_ffmpeg_camera.cpp:80: error: ‘av_log_set_level’ was not declared in this scope
zm_ffmpeg_camera.cpp:82: error: ‘av_register_all’ was not declared in this scope
zm_ffmpeg_camera.cpp: In member function ‘virtual int FfmpegCamera::PrimeCapture()’:
zm_ffmpeg_camera.cpp:94: error: ‘mFormatContext’ was not declared in this scope
zm_ffmpeg_camera.cpp:94: error: ‘av_open_input_file’ was not declared in this scope
zm_ffmpeg_camera.cpp:95: error: ‘errno’ was not declared in this scope
zm_ffmpeg_camera.cpp:98: error: ‘mFormatContext’ was not declared in this scope
zm_ffmpeg_camera.cpp:98: error: ‘av_find_stream_info’ was not declared in this scope
zm_ffmpeg_camera.cpp:99: error: ‘errno’ was not declared in this scope
zm_ffmpeg_camera.cpp:103: error: ‘mFormatContext’ was not declared in this scope
zm_ffmpeg_camera.cpp:108: error: ‘CODEC_TYPE_VIDEO’ was not declared in this scope
zm_ffmpeg_camera.cpp:118: error: ‘mCodecContext’ was not declared in this scope
zm_ffmpeg_camera.cpp:118: error: ‘mFormatContext’ was not declared in this scope
zm_ffmpeg_camera.cpp:121: error: ‘mCodec’ was not declared in this scope
zm_ffmpeg_camera.cpp:121: error: ‘avcodec_find_decoder’ was not declared in this scope
zm_ffmpeg_camera.cpp:125: error: ‘mCodec’ was not declared in this scope
zm_ffmpeg_camera.cpp:125: error: ‘avcodec_open’ was not declared in this scope
zm_ffmpeg_camera.cpp:129: error: ‘mRawFrame’ was not declared in this scope
zm_ffmpeg_camera.cpp:129: error: ‘avcodec_alloc_frame’ was not declared in this scope
zm_ffmpeg_camera.cpp:132: error: ‘mFrame’ was not declared in this scope
zm_ffmpeg_camera.cpp:135: error: ‘PIX_FMT_RGB24’ was not declared in this scope
zm_ffmpeg_camera.cpp:135: error: ‘avpicture_get_size’ was not declared in this scope
zm_ffmpeg_camera.cpp:138: error: ‘AVPicture’ was not declared in this scope
zm_ffmpeg_camera.cpp:138: error: expected primary-expression before ‘)’ token
zm_ffmpeg_camera.cpp:138: error: ‘avpicture_fill’ was not declared in this scope
zm_ffmpeg_camera.cpp:141: error: ‘SWS_BICUBIC’ was not declared in this scope
zm_ffmpeg_camera.cpp:141: error: ‘sws_getCachedContext’ was not declared in this scope
zm_ffmpeg_camera.cpp: In member function ‘virtual int FfmpegCamera::Capture(Image&)’:
zm_ffmpeg_camera.cpp:159: error: ‘AVPacket’ was not declared in this scope
zm_ffmpeg_camera.cpp:159: error: expected ‘;’ before ‘packet’
zm_ffmpeg_camera.cpp:163: error: ‘mFormatContext’ was not declared in this scope
zm_ffmpeg_camera.cpp:163: error: ‘packet’ was not declared in this scope
zm_ffmpeg_camera.cpp:163: error: ‘av_read_frame’ was not declared in this scope
zm_ffmpeg_camera.cpp:172: error: ‘mCodecContext’ was not declared in this scope
zm_ffmpeg_camera.cpp:172: error: ‘mRawFrame’ was not declared in this scope
zm_ffmpeg_camera.cpp:172: error: ‘avcodec_decode_video2’ was not declared in this scope
zm_ffmpeg_camera.cpp:182: error: ‘mRawFrame’ was not declared in this scope
zm_ffmpeg_camera.cpp:182: error: ‘mCodecContext’ was not declared in this scope
zm_ffmpeg_camera.cpp:182: error: ‘mFrame’ was not declared in this scope
zm_ffmpeg_camera.cpp:182: error: ‘sws_scale’ was not declared in this scope
zm_ffmpeg_camera.cpp:188: error: ‘mCodecContext’ was not declared in this scope
zm_ffmpeg_camera.cpp:188: error: ‘mFrame’ was not declared in this scope
zm_ffmpeg_camera.cpp:193: error: ‘av_free_packet’ was not declared in this scope
make[2]: *** [zm_ffmpeg_camera.o] Error 1
make[2]: Leaving directory `/root/cam/ZoneMinder-1.25.0/src'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/root/cam/ZoneMinder-1.25.0'
make: *** [all] Error 2
Anthon
77k42 gold badges159 silver badges217 bronze badges
asked Aug 18, 2013 at 1:18
Turns out the latest stable release of ffmpeg (1.2.2) does not go along with ZoneMinder 1.25.0.
Installing the 0.9 version of ffmpeg solved this issue.
wget http://www.ffmpeg.org/releases/ffmpeg-0.9.tar.gz
tar -xzvf ffmpeg-0.9.tar.gz
cd ffmpeg-0.9
./configure --enable-gpl --enable-shared --enable-pthreads
make
make install
make install-libs
answered Aug 18, 2013 at 1:18