What does the compiler error “missing binary operator before token” mean?

爱⌒轻易说出口 提交于 2019-12-17 09:46:43

问题


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?


回答1:


This is not a compiler error, it is a preprocessor error. It seems to occur 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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/21338385/what-does-the-compiler-error-missing-binary-operator-before-token-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!