简体   繁体   中英

Variably modified at file scope error

I've a perfectly working program that has a following struct

typedef struct SERVER{
    int id;
    char ip_addr[MAX_IP + 1];
    int port;
}SERVER;

MAX_IP is defined in a header file.

#define MAX_IP strlen("255.255.255.255")

This code runs fine on my local machine. The moment I upload it to a server I get the following compilation error.

objs.h:4:10: error: variably modified ‘ip_addr’ at file scope
     char ip_addr[MAX_IP + 1];

What could possibly be wrong.

typedef struct SERVER{
    int id;
    char ip_addr[MAX_IP + 1];
    int port;
}SERVER;

The structure definition above is not valid in C as stuctures members are not allowed not have variable length array type. MAX_IP + 1 has to be an integer constant and in C a function call (your MAX_IP being defined as strlen("255.255.255.255") ) is not a constant.

To fix your issue you can use this definition of MAX_IP instead:

#define MAX_IP  (sizeof "255.255.255.255" - 1)

which has the same value and is a integer constant.

strlen("255.255.255.255")

Is not a constant. And thus, you're breaking the rules by trying to have a variable length array.

Since you are always taking a strlen of a fixed string, would it be possible to change the definition of MAX_IP to a constant, rather than embed a function call every time the macro is used? If the user of your header doesn't have (or can't have) the standard library built in, they will have issues.

If not, can you elaborate more on what the differences are between the server and your machine where the code works?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM