GNU C Compiler Internals/Creating a Compiler Extension 4 1

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Function overloading in C

[edit | edit source]

The C function overloading extension aims at including a C++ feature to C language which allows use functions with the same name but different argument types. The cfo/test.c example of GEM demonstrates this feature:

void ec_aa_add(int from, char *to);
void ec_aa_add(int from, int to);

are used to add an element to a pool data structure.

The idea behind the implementation of the extension is to rewrite each function declaration so that the new name includes the type information of function's arguments. In the above case, the modified names are ec_aa_add_int_char_ptr and ec_aa_add_int_int. The compilation continues normally with the updated names.

Because of the above modification, the call names need modification as well. The renaming takes into account the types of the arguments so that the appropriate function is called. For example, the compiler will modify




Three hooks are used in this extension. Functions cfo_start_decl() and cfo_start_function() intercept declarations. They call cfo_alias_decl() that replaces the name using argument types. To preserve the library code for the programs that do not use CFO extension, the following technique is used. If the function name is encountered first time, an alias is created to its old name so that one can invoke the function using either of them. Thus, the legacy code will use the old name, while the CFO-compiled code will use the type-augmented name. Finally, the declaration name is updated to include type information.

Hook cfo_build_function_call() is invoked from the parser when a new function call is found. It replaces the name of callee function with the name that takes into account the types of actual-in arguments.