Include a file multiple times with different macro

2019-09-08 11:45发布

I got a file that contains generic methods for working with arrays of different number types (the basic ideas are described in Pseudo-generics in C). The type can be specified by setting a TYPE macro. It looks like this (just a part of it):

array_analyzers.c:

#ifndef TYPE
#error TYPE isn't defined
#endif

#define CONCAT(x, y) x ## y
#define GET_NAME(BASE, TYPE) CONCAT(BASE, TYPE)

TYPE GET_NAME(get_minimum_, TYPE) (TYPE nums[static 1], int len){
    TYPE min = nums[0];

    for (int i = 1; i < len; i++) {
        if (nums[i] < min) {
            min = nums[i];
        }
    }

    return min;
}

#undef CONCAT
#undef GET_NAME
#undef TYPE

Now, I created a header file that looks like this:

array_analyzers.h:

#ifndef TYPE
#error TYPE isn't defined
#endif

#define CONCAT(x, y) x ## y
#define GET_NAME(BASE, TYPE) CONCAT(BASE, TYPE)

TYPE GET_NAME(get_minimum_, TYPE) (TYPE nums[static 1], int len);

#undef CONCAT
#undef GET_NAME
#undef TYPE

Finally, I want to use this from main.c:

#include <stdio.h>

#define TYPE int
#include "array_analyzers.h"
#define TYPE double
#include "array_analyzers.h"

int main(void){
  int nums[] = {1, 2, 3};
  printf("%i\n", get_minimum_int(nums, 3));
}

However, I'm getting the following error message:

array_analyzers.c:2:2: error: #error TYPE isn't defined

What exactly is wrong here? It works when I run the preprocessor first and create separate files with the right contents, but that is just awful.

标签: c macros include
1条回答
可以哭但决不认输i
2楼-- · 2019-09-08 12:38

You don not declare the int in the loop at the beginning of a scope, but in a for loop. If you are using gcc you can add -std=c99 compiler option to accept this code.

in this function is a standard loop that should alway be accepted. In this function int i is declared at the beginning of a scope.

int
ansi_c (){
    int i;
    for ( i = 0 ; i < 10; i++ ){

    }
}

and in this function is a loop that is only accepted when -std=c99 or std=gnu99 is added. This function declares the int inside a loop.

c99(){
    for (int i = 0; i < 10; i++ ){

    }
}
查看更多
登录 后发表回答