Search code examples
gccpragmasyntax-checking

GCC syntax check ensure NULL passed as last parameter in function call with variable arguments


I want to do something similar to how, in GCC, you can do syntax checking on printf-style calls (to make sure that the argument list is actually correct for the call).

I have some functions that take a variable number of parameters. Rather than enforce what parameters are sent, I need to ensure that the last parameter passed is a NULL, regardless of how many parameters are passed-in.

Is there a way to get GCC to do this type of syntax check during compile time?


Solution

  • You probably want the sentinel function attribute, so declare your function like

    void foo(int,double,...) __attribute__((sentinel));
    

    You might consider customizing your GCC with a plugin or a MELT extension to typecheck more precisely your variadic functions. That is, you could extend GCC with your own attributes which would do more precise checks (or simply make additional checks based on the names of your functions).

    The ex06/ example of melt-examples is doing a similar check for the jansson library; unfortunately that example is incomplete today October 18th 2012, I am still working on it.

    In addition, you could define a variadic macro to call such a function by always adding a NULL e.g. something like:

    #define FOO(N,D,...) foo((N),(D),##__V_ARGS__,NULL)
    

    Then by coding FOO(i+3,3.14,"a") you'll get foo((i+3),(3.14),"a",NULL) so you are sure that a NULL is appended.