C function seemingly not defined anywhere! - c

I'm looking at the vim source code, specifically the file normal.c, and I see this function nv_operator being used, but it's not defined anywhere (I grepped the entire src directory)
It's only declared as:
static void nv_operator __ARGS((cmdarg_T *cap));
I've looked up the definition of __ARGS but it's just ... nothing (pretty much)
in vim.h:
#define __ARGS(x) x
So what could be going on? Is this some kind of C technique to create a dummy function or something?

There is a definition present here:
/*
* Handle an operator command.
* The actual work is done by do_pending_operator().
*/
static void
nv_operator(cap)
cmdarg_T *cap;
....
That style of definition is using an identifier list for its parameters. The style is deprecated (obsolescent) but can still be used in C. The identifiers are named in the parameter list, and their type are named in declarations that immediately follow the function declarator but precede the functions body.
The __ARGS macro is there to handle compilers that don't know about prototypes for functions (the other form to declare parameters - with type and name combined directly in the function parameter list). It would then just emit no parameters at all in declarations, i think.
Update: See this code in vim.h:
#if defined(MACOS) && (defined(__MRC__) || defined(__SC__))
/* Apple's Compilers support prototypes */
# define __ARGS(x) x
#endif
#ifndef __ARGS
# if defined(__STDC__) || defined(__GNUC__) || defined(WIN3264)
# define __ARGS(x) x
# else
# define __ARGS(x) ()
# endif
#endif

It's simply a forward declaration, so that the function is known to the C compiler (and can be used (called from other functions)) before it's actually defined (in line 8247). The actual formatting of the definition (which includes newlines) makes it hard to grep for it's existence.
Don't get distracted by the __ARGS macro. It's only a compatibility macro for the different function declaration syntaxes of K&R C vs. ANSI C.
In ANSI C a function declaration must look like this:
int getopt(int, char * const *, const char *);
In the (older) Kernighan and Ritchie C http://en.wikipedia.org/wiki/C_(programming_language)#K.26R_C
int getopt();

Its hard to find because of how it is defined:
nv_operator(cap)
appears on a line by itself.

I am not too sure what is going on, but here are some hints to help you in your search:
First of all, the __ARGS macro seems to be there because there may be versions of C where you shouldn't include the args in the declaration of the functions (Notice that the macro is defined differently depending on other preprocessor symbols... the comments say it).
Secondly, searching for the function nv_operator may not be good enough. The function might be generated by macros and such, so you can't search for an explicit definition.... for example, maybe the "nv" prefix is added by the preprocessor.
Hope this helps.

Related

How does function-like macros work, this example

void someOtherFunction(void)
{
...
}
//Is it possible to call the #define like this, in the global scope? When does the execution come here?
SYSTEM_CONTROL_REGISTER_INIT_FUNCTION( credHandlerInit, LEVEL_APPLICATION, SYSTEM_CONTROL_ORDER_DONT_CARE );
void credHandlerInit(void)
{
portBASE_TYPE result;
result = xTaskCreate( credHandlerTask,
(portCHAR *) MBS_CFG_TASK_NAME_CRED_HANDLER,
MBS_CFG_TASK_STACK_CRED_HANDLER,
NULL,
MBS_CFG_TASK_PRIO_CRED_HANDLER,
&credHandlerTaskHandle );
}
and in a .h-file the following macro is defined:
#define SYSTEM_CONTROL_REGISTER_INIT_FUNCTION( _initFunctionName, \
_initLevel, \
_initOrder ) \
\
void _initFunctionName( void ); \
\
SystemControlInitListRecord const systemControlInitRecord_ ## _initLevel ## _initOrder ## _ ## _initFunctionName \
__attribute__ ((section (".systemControlInitList"))) \
= { \
.name = #_initFunctionName, \
.syncedInitFunction = NULL, \
.unsyncedInitFunction = _initFunctionName, \
.level = _initLevel, \
.order = _initOrder, \
.initType = SYSTEM_CONTROL_RTOS_RUNNING \
}; \
\
void _initFunctionName( void )
What I don't understand is how this function is called?
I do not see any call to this function in the code.
Can someone explain how this work?
Is the code below valid, calling the macro like this?
//main.c
#define SOMETHING(x) (someVariable = x)
static uint32_t someVariable;
SOMETHING(5);
int main(void)
{
printf("%d", someVariable); //should print 5 here then?
}
The intention of this code is the following:
The macro declares a function named credHandlerInit. This name is passed to the _initFunctionName macro parameter name. Whoever wrote the macro didn't quite know what they are doing, so we end up with two function declarations void credHandlerInit(void );, which is OK but very fishy. Perhaps they optionally meant the macro to be followed by the function definition in the form of { ... }. At any rate, not the best idea.
The whole SystemControlInitListRecord const part declares a read-only struct of that type, then names it systemControlInitRecord_LEVEL_APPLICATION_SYSTEM_CONTROL_ORDER_DONT_CARE _credHandlerInit. This is where I'd start to suspect that the programmer who wrote this is paid per letter written... and also that they were not an expert at C programming.
NOTE: identifiers longer than 32 characters is a safety hazard in C, see 5.2.4.1 translation limits. So if this function name will act as an external identifier, which we have all the reasons to believe since it ain't static, a conforming compiler may not be able to distinguish between different functions with the systemControlInitRecord_LEVEL_APPLICATION_ prefix. There's no guarantee of "name mangling" but the compiler might end up generating source that calls the wrong function from the external caller side.
In practice, modern compilers tend to distinguish between far more than 32 characters, but they aren't guaranteed to do so. Best case scenario, the code is non-portable between standard compilers. Worst case, the whole code will go completely haywire on the designated compiler.
So this is a subtle and severe bug who the original programmer was not aware of. Someone will need to slap 'em from inventing such ridiculously long identifier names. It is both dangerous and completely unreadable.
The __attribute__ ((section (".systemControlInitList"))) is a common non-standard extension used by gcc and a bunch of other compilers for creating custom memory segments. These names need to correspond to a memory section in the linker script. Why this variable needs to reside in that memory section, I don't know, but this is obviously part of some embedded system where named memory sections are quite common practice (used for bootloaders, on-chip library code, NVM variables, ISRs, flash drivers etc etc).
The whole { .name = #_initFunctionName, .syncedInitFunction = NULL, ... part is a struct initializer list utilizing _designated initializers. The first member is apparently a string and the # "stringification" operator turns the name string into "credHandlerInit".
The void _initFunctionName( void ), as already mentioned, might optionally begin the function definition, which is then apparently expected to continue on the caller-side. Or otherwise the ; in the macro call makes this a 2nd function declaration.
As you can hopefully tell from my comments, this code is very badly written by someone obsessing in making things as needlessly complicated as possible, whereas the truly good C programmers try to make things as simple as possible.
I would guess it is part of some smelly RTOS source and used for user-side task creation or similar? I would stay clear of this source, since there's lots of code smell and I already found one severe bug from just reading one single macro.
A "function-like macro" just means a macro which takes arguments.
In this example you have a macro which takes arguments but it is not being used like a function at all.
This macro expands to a constant object definition. The object is a structure with information about a function and when to call it. The object is placed in a custom non-standard section called ".systemControlInitList".
In order to use this code you must have a corresponding custom linker control script (usually called something.ld). This will collect all the objects that are placed in the custom section and put them somewhere in the program image, probably ROM. It will put some custom symbol at the the start of the block of such objects, and probably another symbol at the end.
There will then need to be some custom code that runs as part of your application start or boot sequence that looks for that symbol and executes all the functions referred to by the array of structure.

Confusion between header file macro declaration and pre-processor macro declaration

I am new to C, so please help me with an answer before downvoting, it will help me a lot.
The definition of header file states that-
A header file consists of C function declaration and macro definitions to be shared between different files.
And the definition of C Preprocessor states that-
The C preprocessor is a macro preprocessor that transforms your program before it is compiled.All preprocessor directives begin with the # symbol.
My question is the macro declaration are done using # symbol in a program, does it depend on inclusion or exclusion of any header file, also how to find whether a particular file has a pre-defined macro declaration in it.
For example-
Say a file 'ani.h' has a macro declaration,
#define anii 2
So, once I include this file, I am allowed to use the CNAME i.e. aniidirectly?
It is easier if you look at this form the view of what the pre-processor actually does.
It reads a file and replaces text and then output a new file. The new file is sent to the compiler. The pre-proc knows nothing about C code, its just a text manipulation engine
#include xxxx
says, 'replace this line by the contents of that file'
#define FOO BAR
says, 'whenever you see FOO replace it by BAR
There are also some simple conditionals: #if etc
A macro is simply a FOO BAR replacement, usually FOO is small and BAR is large.
Although they can be used to do some nice metaprogramming tricks as well as conditional programming, macros most basic use is to make programmers lives easier via syntactic sugaring. Before compiling your code, the preprocessor module will substitute all the macros by the terms they represent, so everything you define must have been declared somewhere above the point where the macro is first used. So if you do:
#include <stdio.h>
#include <math.h>
#define MY_MACRO(x) for(int i=0; i<(x); ++i) printf("%d\n", func((x),i);
int func(int n, int m) {return pow(n, m);}
int main()
{
int a = 10;
MY_MACRO(a)
return 0;
}
The preprocessor will substitute all occurrences of MY_MACRO in your code by the loop that was defined after it. The code will then be sent to compilation. When the compiler reaches the line where the macro is used, it is necessary that printf and func are declared somewhere above this line, just as if you were writing the code without the macro. (Note that printf and pow are declared in the headers included before the definition and func is declared after the definition, but them three are declared before the first use of the macro.)
In what concerns to knowing which macros are declared inside some lib and which aren't, I believe the only way is to check the header files you are using or to read their documentation. But if you know that some specific macro may or may not be declared, you can test it using the code below:
#ifdef SOME_MACRO
printf("SOME_MACRO defined!\n");
#else
printf("SOME_MACRO not defined!\n");
#endif

What are these function and parameter annotations?

The source code for busybox's syslogd implementation contains some annotations I'm unfamiliar with. The language is C, not C++.
int syslogd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int syslogd_main(int argc UNUSED_PARAM, char **argv)
Specifically, MAIN_EXTERNALLY_VISIBLE and UNUSED_PARAM.
What exactly are these annotations doing? Where can I read more about them and other annotations?
Are these part of the C standard, or are they compiler extensions? If they are compiler extensions, how widely supported are they?
I assume the first one is why this file doesn't have a main() function. If these are compiler extensions rather than part of the standard, does this mean this file can't be meaningfully compiled as-is by a compiler that adheres only to the C standard?
Why did they declare a prototype of the syslogd_main function immediately before the full definition? Can the MAIN_EXTERNALLY_VISIBLE annotation only be applied to function prototypes?
1. What exactly are these annotations doing?
See include/platform.h and include/libbb.h
UNUSED_PARAM expands to __attribute__ ((__unused__)). It specifies the variable (argc in your example) as "possibly unused" and disables the "unused variable" warning.
From the GCC manual [Specifying Attributes of Variables]:
unused
This attribute, attached to a variable, means that the variable is meant to be possibly unused. GCC will not produce a warning for this variable.
MAIN_EXTERNALLY_VISIBLE expands to EXTERNALLY_VISIBLE and then to __attribute__(( visibility("default") )). It controls the visibility of the function.
From the GCC manual [Declaring Attributes of Functions]:
... On ELF, default visibility means that the declaration is visible to other modules and, in shared libraries, means that the declared entity may be overridden.
From include/libbb.h:
/* We need to export XXX_main from libbusybox
* only if we build "individual" binaries
*/
#if ENABLE_FEATURE_INDIVIDUAL
#define MAIN_EXTERNALLY_VISIBLE EXTERNALLY_VISIBLE
#else
#define MAIN_EXTERNALLY_VISIBLE
#endif
2. Are these part of the C standard, or ...?
No, those are macros defined in the BusyBox project.
3. I assume the first one is why this file doesn't have a main() function. ...
No. BusyBox combines many utilities into a single executable. That explains the "lack of a main() function" in syslogd.c.
4. Why did they declare a prototype of the syslogd_main function immediately before the full definition? ...
From the GCC manual [Declaring Attributes of Functions]:
The keyword __attribute__ allows you to specify special attributes when making a declaration.

Preprocessor macro definitions used with C function definition

I'm studying the SQLite source code (in c), but there are some things I can't figure out what they are, and I hope you can give me a hand.
I know c, c++ and JAVA basics but I have never seen something like this and I don't know how to search for it.
In a c file, there are the next definitions (among others):
#ifndef SQLITE_CDECL
# define SQLITE_CDECL
#endif
#ifndef SQLITE_API
# define SQLITE_API
#endif
And then the above definitions are used like this:
SQLITE_API int SQLITE_CDECL sqlite3_conf(int, ...){
//code
I know "SQLITE_API" and "SQLITE_CDECL" are not the return types, function names, keywords, K&R style nor variable modificators...
Why are this words placed like that in the function? What are they for?
They're used to modify the attributes of the functions on different platforms or when building certain ways. Most of the time there may be no need for them, but in certain situations they may be useful, e.g. using __declspec(dllexport) when building a DLL or using static when including the file directly instead of having the linker perform linkage between the object files.
These two declarations look like they exist so that they can be defined differently to support certain quirks of development on Windows. Note that on the #define lines, they aren't defined to any value. This means that they will be replaced with nothing that the parser sees. So, SQLITE_API int SQLITE_CDECL sqlite3_conf(int, ...){ will end up being reduced to int sqlite3_conf(int, ...){ after the preprocessor runs. On Windows, they can be defined differently to support building DLLs with __declspec (see https://msdn.microsoft.com/en-us/library/dabb5z75.aspx) and specifying calling conventions (see https://msdn.microsoft.com/en-us/library/zkwh89ks.aspx).

Is this an interface or a function prototype?

I'm trying to read a project documentation. Under the title Prototype, I'm having this code :
VisionAPI_RETURN VisionAPI VisionInterf_ImageAttach(
VisionAPI_HANDLE ImageHandle ,
uint32_t NumImages
);
The project's interfaces will be build in C, when the functions will be in C++.
When reading the documentation, I read prototype, so I supposed it is "functions prototypes". When reading more, I find the author sometimes using the term "function" and sometimes "interface". I know how to make an interface in C++ but not in C.
So is the code above about interface or function prototype?
Otherwise, how to create an interface in C language? Is it by creating structure (struct) ?
I hope my question is not stupid. I'm a Java developer, and a C/C++ simple student.
This declares the function, without providing an implementation (the definition). So, you could say this is an interface. You just tell the compiler: "Hey, there is a function with the name VisionInterf_ImageAttach" so it doesn't complain when you call it. More about declaration vs. definition.
This, of course depends on what VisionAPI_RETURN and VisionAPI resolve to, assuming they are macros.
There is no such thing in C language as an interface: in addition to primitive types and pointers, the language supports structs and functions; that's all you have to work with.
Your code shows an example of a forward declaration of a function. Interfaces to C modules consist of multiple such declarations, along with declaration of structs that these functions use.
(Adding to the already useful info given by #bitmask and #dasblinkenlight)
In C a function prototype is, roughly, the declaration of a function signature, i.e. the declaration of the function name, return type and parameter list types (i.e. the types of the parameters the function accepts, in their respective order).
Therefore, in a sense, the prototype of a function can be viewed as the interface of the function towards client code (in this case the term interface is used in a general way, unlike what it means in OOP and Java in particular).
As a simpler example, suppose you defined a function like this:
int MyFunc( double x, char * z )
{
// function body code
}
then its prototype would be:
int MyFunc( double x, char * z );
or even
int MyFunc( double, char * );
since parameter names are optional in function prototypes.
There is no mechanism in C for creating an equivalent replica to Java interfaces, although often programmers refer to specially crafted C header files as "interfaces". These header files are filled with function prototypes and other declarations that represent the "interface" of the library they belong toward client code.
Therefore client code can #include those header files to access the facilities offered by the library without knowing its implementation (here is the "interface" thing), which usually is resolved at link time (or at run-time if dynamic linking is involved).
Edit (to answer a comment)
What you see before function name is probably some macro trick. Since I don't know what's the context I can only guess. The two identifiers VisionAPI_RETURN VisionAPI are most probably defined as macros. From their names I guess that the first expands to the actual return type, while the second could be either an empty macro (usually used to mark some category of declarations) or expands to some compiler-specific keyword combination, usually used to declare the function low-level calling convention.
For example, somewhere there could be these macro definitions:
#define VisionAPI_RETURN int
#define VisionAPI
so that, after the preprocessor has finished its work, the compiler will see this:
int VisionInterf_ImageAttach(
VisionAPI_HANDLE ImageHandle,
uint32_t NumImages
);
Another example - if those macros are defined like this:
#define VisionAPI_RETURN struct MyReturn
#define VisionAPI __stdcall
then the prototype will be expanded like this:
struct MyReturn __stdcall VisionInterf_ImageAttach(
VisionAPI_HANDLE ImageHandle,
uint32_t NumImages
);
In this case the return type would be struct MyReturn, while the __stdcall keyword would indicate the "stdcall" calling convention (the __stdcall keyword is used by Microsoft compilers). This resulting syntax is an extension to standard C syntax (many compilers have some kind of such extensions).

Resources