Error missing binary operator before token

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

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?

Brian Tompsett - 汤莱恩's user avatar

asked Jan 24, 2014 at 17:08

AShelly's user avatar

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

AShelly's user avatar

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

Gabriel Devillers's user avatar

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

Yusuf Gören's user avatar

check the direct. no space,no special
exp:
add_subdirectory(Main)->add_subdirectory(main)

answered Sep 8, 2020 at 9:03

asdgasg's user avatar

3

@dblanm

When making make in the build directory, using sudo make, make or make -j4
It gives me the error
home…/fcl/octree.h error: missing binary operator before token «(«
#if OCTOMAP_VERSION_AT_LEAST(1,8,0)
^

…. and it follows

I change it to #if OCTOMAP_VERSION_AT_LEAST(1.8.0)
but it didn’t worked
Anyone with same problem that knows how to fix it?

Thanks in advance!

@dblanm

The code failing is this one:

/// @return ptr to child number childIdx of node
OcTreeNode* getNodeChild(OcTreeNode* node, unsigned int childIdx)
{
#if OCTOMAP_VERSION_AT_LEAST(1,8,0)
return tree->getNodeChild(node, childIdx);
#else
return node->getChild(childIdx);
#endif
}

I have to say that I have installed last version of octomap, and checked it in /usr/local/share/octomap/package.xml

@jslee02

@dblanm

I am sorry but I am a bit new modifying this.
I modified the fcl/config.h.in and added:
#if FCL_HAVE_OCTOMAP
#define OCTOMAP_MAJOR_VERSION @OCTOMAP_MAJOR_VERSION@
#define OCTOMAP_MINOR_VERSION @OCTOMAP_MINOR_VERSION@
#define OCTOMAP_PATCH_VERSION @OCTOMAP_PATCH_VERSION@

#define OCTOMAP_VERSION_AT_LEAST(x,y,z)
(OCTOMAP_MAJOR_VERSION > x || (OCTOMAP_MAJOR_VERSION >= x &&
(OCTOMAP_MINOR_VERSION > y || (OCTOMAP_MINOR_VERSION >= y &&
OCTOMAP_PATCH_VERSION >= z))))

#define OCTOMAP_VERSION_AT_MOST(x,y,z)
(OCTOMAP_MAJOR_VERSION < x || (OCTOMAP_MAJOR_VERSION <= x &&
(OCTOMAP_MINOR_VERSION < y || (OCTOMAP_MINOR_VERSION <= y &&
OCTOMAP_PATCH_VERSION <= z))))
#endif // FCL_HAVE_OCTOMAP

and also included <fcl/config.h> (tested also fcl/config.h.in) in octree.h, and still have the same error.
What am I missing?

@jslee02

First, you wouldn’t include config.h.in but config.h which is generated by CMake.

To clarify, do you mean the current master branch couldn’t be built on your system? Did you rerun cmake as well?

Also, why are you modifying config.h.in? could you elaborate what you modified in config.h.in? Because I can’t see any difference between what you posted and the original config.h.in.

@dblanm

As you said, I couldn’t built the master branch. I downloaded it again and changed octree.h before making cmake and the error still occurs.

@jslee02

Couldn’t build it as you downloaded without any modification?

And, why are you changing octree.h again?

@dblanm

No, I couldn’t because it gives me the error I first posted.

And I was changing octree.h to add the config.h to see it that corrected the error, but it didn’t work. What I did was to add the config and to change OCTOMAP_VERSION_AT_LEAST(1,8,0) for OCTOMAP_VERSION_AT_LEAST(1.8.0). (, for .)

@jvgomez

This is the same problem I was having when I updated the PR. However, in the CI and for @jslee02 it worked fine. Perhaps is something related to the compiler? I am using gcc version 4.8.5 (Ubuntu 4.8.5-2ubuntu1~14.04.1)

In any case, @dblanm changing , for . will not solve anything as the macro is prepared to receive 3 parameters (MAJOR, MINOR, PATCH).

@pbarragan

Hi, I also ran into this problem after trying to make a clean clone of FCL. I eventually had to try to force compilation ignoring octomap to get it to work (by changing CMakeCache.txt because I didn’t know how to do it the right way). FCL works now, but I’m not sure why I got this error or how I would get around it if I wanted to use octomap. Any ideas on the compiler issue? I am using gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4. Is this problem an error with just the files included in FCL or could it have to do with the octomap package or other dependencies?

@jvgomez

@pbarragan I introduced recently this issue :( Since Octomap has changed the API, I wanted to make FCL able to work with both Octomap version >=1.8.0 and <1.8.0, that is why those compilation-time macros are introduced. It was not working on my computer (I tried many many different things), but for @jlsee02 it worked, and also in the CI. Surprisingly, I was even able to create a debian package out of it in my computer.

@jslee02 which compiler did you use? Because Iused GCC4.8.4 as well. What does the CI use? I guess that, in any case, we should modify this to a simple #define OCTOMAP_GREATER_THAN_1_8 for instance. If you agree I will carry out the changes asap.

@jslee02

I’m using gcc (Ubuntu 4.8.5-2ubuntu1~14.04.1) 4.8.5, and Travis uses gcc (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4.

I couldn’t reproduce the reported problem, and actually don’t think it’s a compiler problem. It would be nice if anyone can reproduce the problem by creating a test repo or any other way.

@pbarragan

@jslee02 I’d be happy to help as the error happens on my system, but I’m not sure how to create a repo that would produce the problem on any system. I can provide any information that’s helpful, but if someone could point me to what to provide or how to create said repo, I’d appreciate it as I’m a bit new to how to debug this.

@jslee02

For a simple test, can you replace all the OCTOMAP_VERSION_AT_LEAST(1,8,0) with OCTOMAP_MAJOR_VERSION and let me know what you get?

@pbarragan

I made the change, removed the previous build directory, cmake .. in a new build directory and make and it seemed to work just fine. I then ran ./tests/test_fcl_distance and that also worked with no errors. make install also worked fine. Seems like it fixed that part.

@jvgomez

A quick note, I think at this point is much easier to follow something like Gazebo guys do:

#if GAZEBO_VERSION_MAJOR >=7
....

Maybe we should do

#if OCTOMAP_MAJOR_VERSION >= 1
# if OCTOMAP_MINOR_VERSION >= 8
...
# endif
#endif

Or just simple collapse all this into a macro #if OCTOMAP_VERSION_GREATER_1.8

This was referenced

Jul 21, 2016

@wjwwood

I believe the pull request I just opened should fix this: #142

Basically, if you already have fcl installed, then in certain situations you can get the installed fcl/config.h rather than the one generated for the local build. That’s why this never showed up in CI.

@jslee02

@dblanm

I completley removed fcl and octomap libraries,
I installed octomap by CI folder and then installed fcl, the problem no longer exits.
Thank you for the solution.

@dblanm

I am testing now fcl octree and octomap using ROS and it compiles, then i think the problem is well solved.

@jslee02

Okay, it seems the issue is resolved! Closing.

@k-maheshkumar

Hey, I just checked out the branch fcl-0.5 and tried to build, but got the same error. Please help to build the package.
Thank you.

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's user avatar

karel

107k93 gold badges263 silver badges290 bronze badges

asked Apr 26, 2020 at 19:15

parser1234's user avatar

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

karel's user avatar

karelkarel

107k93 gold badges263 silver badges290 bronze badges

1

Форум РадиоКот :: Просмотр темы — Проблема макросов в классах.


Автор:  Pink-Pank [ Чт дек 18, 2014 08:42:24 ]
Заголовок сообщения:  Проблема макросов в классах.

Всем добрый день!

Частенько использую макросы для автоматизированного расчета загружаемых в регистры значений. Например:

Код:

#define F_CPU 1200000UL
#define TIMER_FREQUENCY_HZ   1013   // Частота срабатывания таймера в герцах.
#define LOAD_VALUE   ((unsigned char)( round(((double)F_CPU / (double)TIMER_FREQUENCY_HZ / 8 — 1))))
….

OCR0 = LOAD_VALUE;   // 8 — предделитель таймера. Режим CTC

В общем, если использую подобные макросы при работе с регистрами напрямую или передавая значение функции, то все ОК.
А на этот раз решил поиграться с классами. Создал класс и появилась проблемка. При передаче функции класса числового значения все ОК. Либо если передаю макрос, где нет приведения типов, то тоже все ОК. А вот если в макросе есть приведение типа переменной, то компилятор начинает материться, что:
missing binary operator before token «(«
Кто может сталкивался с такой проблемой? Как ее решить? Я так предполагаю, что препроцессор сначала подставляет выражение из макроса, а уже потом его рассчитывает. Может можно как-то заставить его сначала рассчитать это значение, а потом уже подставлять куда надо? Или как-то альтернативно решить эту проблему?
Какой ентому гаду бинарный оператор нужен?

И еще. Если я функции класса передаю не переменные, а числовые константы, можно как-то компилятор заставить, чтобы функция не принимала значения через стек (или регистры), а генерировалась инлайном с подстановкой нужных значений, не качая их из стека? Это с учетом того, что она в классе и простой инлайн не катит, но вызывается при этом всего один раз.


Автор:  ploop [ Чт дек 18, 2014 09:34:27 ]
Заголовок сообщения:  Re: Проблема макросов в классах.

У вас точка с запятой в макросе.

Pink-Pank писал(а):

Я так предполагаю, что препроцессор сначала подставляет выражение из макроса, а уже потом его рассчитывает

Именно так.

Pink-Pank писал(а):

Если я функции класса передаю не переменные, а числовые константы, можно как-то компилятор заставить, чтобы функция не принимала значения через стек (или регистры), а генерировалась инлайном с подстановкой нужных значений, не качая их из стека?

Нет. Функция есть функция, это машинный код в итоге. Препроцессор не сможет запустить её на исполнение в результате компиляции и оставить только результат, так как неизвестно, что там внутри функции вы наворотили.
Ой, кажется не так вас понял
И, кстати, что за классы вы используете? У вас C++?

Цитата:

то с учетом того, что она в классе и простой инлайн не катит, но вызывается при этом всего один раз.

С чего это не может быть инлайновых методов? Вполне могут.


Автор:  Pink-Pank [ Чт дек 18, 2014 09:54:36 ]
Заголовок сообщения:  Re: Проблема макросов в классах.

В макросе у меня нет точек с запятой. Это я просто здесь «намешал» код и макросы. Щас поправлю.
Да, я в студии 6 на си ++ изголяюсь. Хотя можно было бы все проще оформить — просто для опыта решил через класс.

Цитата:

С чего это не может быть инлайновых методов? Вполне могут.

Не знаю. При попытке оформить метод как инлайн компилятор материться, что функция из класса не может вызываться, как инлайная. Думаю, проблема в области видимости внутренних функций классов или что-то в этом духе.. Ведь если сделать два разных объявления классов с одинаковым набором внутренних переменных, потом создать эти два класса и попытаться присвоить значения одного класса другому, то компиль также выдаст ошибку. Думаю, здесь что-то подобное..


Автор:  ploop [ Чт дек 18, 2014 10:10:36 ]
Заголовок сообщения:  Re: Проблема макросов в классах.

Думаю, вы что-то намутили…
Во-первых давайте не будем называть «функции класса», они называются методы, иначе рвёт мозг.

Pink-Pank писал(а):

Ведь если сделать два разных объявления классов с одинаковым набором внутренних переменных, потом создать эти два класса и попытаться присвоить значения одного класса другому, то компиль также выдаст ошибку. Думаю, здесь что-то подобное..

Как вы это делаете? Ничего не понял, покажите пример.


Автор:  Pink-Pank [ Чт дек 18, 2014 10:17:32 ]
Заголовок сообщения:  Re: Проблема макросов в классах.

Методы.. Шметоды.. Это все условности! ))) Главное — полет мысли! ))))))
Но если Вам так привычнее — пожалуйста! Мне не трудно. )

Код:

class First {
   int memi;
   double memd;
};

class Second {
   int memi;
   double memd;
};

class First obj1;
Second obj2 = obj1;   // ошибка: obj1 и obj2 имеют разные типы

Да и как я мог намутить, если передача обычного числа, макроса или переменной прокатывает, а макрос с преобразованием типов вызывает ошибку?
Т.е. если я передаю выражение, скажем F_CPU/16, то все ок. А если выражение (uint16_t)((double)F_CPU/16), то получается облом… Хотя при передаче в простую функцию второе выражение норм работает.


Автор:  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: Проблема макросов в классах.

я ж писал
missing binary operator before token «(«


Автор:  Siarzhuk [ Чт дек 18, 2014 11:28:52 ]
Заголовок сообщения:  Re: Проблема макросов в классах.

Pink-Pank писал(а):

А вот если в макросе есть приведение типа переменной, то компилятор начинает материться, что:
missing binary operator before token «(«
Кто может сталкивался с такой проблемой? Как ее решить? Я так предполагаю, что препроцессор сначала подставляет выражение из макроса, а уже потом его рассчитывает.

С какой проблемой? Где кот с классами? Телепатам гадать не на чем. ;-) На то он и называется ПРЕпроцессором, что он занимается ПРЕпроцессингом — т.е. работает с ко́дом ещё до компиляции.

При непонятных проблемах с макросами нужно включать опцию

-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
Сейчас попробую.
Что-то не генерится этот файл..
Выдает ошибку ld returned 1 exit status collect2.exe 0 0


Автор:  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) {
  // тут присвоЯем поля
  return *this;
}

Pink-Pank писал(а):

Цитата:

-F Preprocess only

не -F, а -E
Сейчас попробую.
Что-то не генерится этот файл..
Выдает ошибку ld returned 1 exit status collect2.exe 0 0

Ну может и не -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/


Description


Vincent Lefèvre



2018-09-18 11:09:21 UTC

The error message

  error: missing binary operator before token "("

from the preprocessor is misleading in general, as in most cases, it is not a binary operator that is missing, but the error is due to the use of sizeof, a cast, or a function-like macro that is not defined. The preprocessor could either output a fixed error message that would reflect the most common misusages, or try to guess what is wrong (like the use of sizeof or something that looks like a cast).

For instance:

$ cat tst.c
#if sizeof(int) > 4
#endif
$ gcc-snapshot -E tst.c
# 1 "tst.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 31 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 32 "<command-line>" 2
# 1 "tst.c"
tst.c:1:11: error: missing binary operator before token "("
1 | #if sizeof(int) > 4
  |           ^

Some users can get confused. For instance, see:
* https://stackoverflow.com/questions/21338385/what-does-the-compiler-error-missing-binary-operator-before-token-mean
* https://cboard.cprogramming.com/c-programming/158452-error-missing-binary-operator-before-token.html
* https://www.linuxquestions.org/questions/programming-9/missing-binary-operator-before-token-4175547706/
* https://forum.kde.org/viewtopic.php?f=269&t=128141


Comment 1


Andrew Pinski



2021-12-19 10:18:43 UTC

clang does a reasonable job at their error message here:
<source>:2:5: error: function-like macro 'sizeof' is not defined
#if sizeof(int) > 4
    ^

ICC is almost as bad as GCC:
<source>(2): error: function call is not allowed in a constant expression
  #if sizeof(int) > 4
      ^

MSVC is worse than GCC:
<source>(2): fatal error C1017: invalid integer constant expression

Подскажите взял конфинги, поместил в марлин немного подредактировал а он не хочет компилироваться.

Моя прошивка

пишет 

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 ===========================================================

See more:

Here is my code:

#if GDK_VERSION_MAX_ALLOWED < GDK_VERSION_MIN_REQUIRED
#error "GDK_VERSION_MAX_ALLOWED must be >= GDK_VERSION_MIN_REQUIRED"
#endif
#if GDK_VERSION_MIN_REQUIRED < GDK_VERSION_3_0
#error "GDK_VERSION_MIN_REQUIRED must be >= GDK_VERSION_3_0"
#endif

#define GDK_AVAILABLE_IN_ALL                  _GDK_EXTERN



#if GDK_VERSION_MIN_REQUIRED >= GDK_VERSION_3_0
# define GDK_DEPRECATED_IN_3_0                GDK_DEPRECATED
# define GDK_DEPRECATED_IN_3_0_FOR(f)         GDK_DEPRECATED_FOR(f)
#else
# define GDK_DEPRECATED_IN_3_0                _GDK_EXTERN
# define GDK_DEPRECATED_IN_3_0_FOR(f)         _GDK_EXTERN
#endif

#if GDK_VERSION_MAX_ALLOWED < GDK_VERSION_3_0
# define GDK_AVAILABLE_IN_3_0                 GDK_UNAVAILABLE(3, 0)
#else
# define GDK_AVAILABLE_IN_3_0                 _GDK_EXTERN
#endif

Now, note, I do not take credit for this code; it was downloaded from [^]

But, I needed this header for one of my source codes; therefore, I copied it. The error occurs within the line #if GDK_VERSION_MAX_ALLOWED < GDK_VERSION_3_0 and of its similar kinds. Can anyone tell me why this is happening?

What I have tried:

Really, I have tried very little, for I have no idea where even to begin!!! I did not put any brackets in «#if GDK_VERSION_MAX_ALLOWED < GDK_VERSION_3_0» but it is still showing me the error missing binary operator before token «(«. Please help!


Quote:

I have no idea where even to begin!

Go back to the place where you downloaded this code and ask there. It is a complete waste of time downloading code from the internet if you do not understand what it is or what it does.

It’s something else in your code: If I copy and paste that lot into a C compiler (or C++) it compiles without problems.
So start by looking at what else you have in there, particularly inside #include files and look for other substitutions. Remember, #DEFINE is a preprocessor operation that effectively does text substitution without any real intelligence. So if you have some other substitutions going on…

It seems that you need to find out what the definitions of these are :

GDK_VERSION_MAX_ALLOWED
GDK_VERSION_MIN_REQUIRED

I don’t know what compiler you have but with VS17 you can right click on the macro and select go to definition and find out what the values of these and where they are defined. Also, just hovering the mouse over them should show their values.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900

  • Home
  • Forum
  • General Programming Boards
  • C Programming
  • Error: missing binary operator before token «(«

  1. 08-02-2013


    #1

    JakubST is offline


    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.


  2. 08-02-2013


    #2

    stahta01 is offline


    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


  3. 08-02-2013


    #3

    JakubST is offline


    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
         ^


  4. 08-02-2013


    #4

    anduril462 is offline


    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.


  5. 08-02-2013


    #5

    JakubST is offline


    Registered User



  6. 08-02-2013


    #6

    grumpy is offline


    Registered User


    Quote Originally Posted by anduril462
    View Post

    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.


  7. 08-02-2013


    #7

    Salem is offline


    and the hat of int overfl

    Salem's Avatar



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 subscribe to a feed

  • 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

  1. Replies: 3

    Last Post: 08-21-2012, 11:50 PM

  2. Replies: 10

    Last Post: 08-09-2012, 12:48 PM

  3. Replies: 9

    Last Post: 07-27-2011, 08:39 PM

  4. Replies: 9

    Last Post: 03-31-2009, 04:23 PM

  5. Replies: 2

    Last Post: 06-29-2007, 07:55 AM

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error mismatched names
  • Error mismatch cisco phone
  • Error minimalism wallpaper engine
  • Error mil off spark ignition
  • Error might have something to do with assetto corsa

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии