error: expected unqualified-id before ‘__extension

2019-08-20 04:10发布

My code is below,

namespace A
{
     namespace B
     {
           unsigned int htonl(unsigned int address)
           {
                return 0;
           }
     }
}

Now I know that htonl is a library function in Linux. Even though I am defining it under namespaces it produces the mentioned error. How can I fix it without changing the function signature?

标签: c++ linux
3条回答
Ridiculous、
2楼-- · 2019-08-20 04:51

Firstly, it's probably worth noting that the library function htonl takes, and returns, a uint32_t. Secondly, as one of the commenters notes, it's a macro, at least on Linux, and is defined as __bswap_32(x) in netinet/in.h.

So your options are limited to ways to avoid the preprocessor substituting the macro expansion before compilation:

a) Rename the function.

b) Avoid the include file. Either moving it after the function definition, or removing it entirely. Note that you'll need to then call this function with a namespace qualification, for example A::B::htonl, or the preprocessor will substitute it there as well.

c) Undefine the macro. This will be problematic if you later want the original definition restored, though.

查看更多
Melony?
3楼-- · 2019-08-20 04:53

The problem here is that htonl, in Linux at least, is a (sometimes) macro that expands to __bswap32, which in turn is a rather long macro (which has __attribute__((extension)) as part of it). Macros do not "care" about namespaces.

If you REALLY want your own function that is called htonl (you probably do not, in general - call it something else), then you can do

#ifdef htonl
#undef htonl
#endif

The #ifdef is there to avoid undefining something that isn't a macro.

Or you could figure out which header file it is that produces htonl (<arpa/inet.h> in my Linux installation) and not include that in your code.

查看更多
趁早两清
4楼-- · 2019-08-20 04:53

Use ::htons call - add "::" before api name.

查看更多
登录 后发表回答