Can C include use macros? - c

I want to include the result of a macro expansion. It seems include only knows <> ""?
This fails:
#define audio sinwave
#ifdef audio
#include audio".c"
/*#include "sinwave.c"*/
#endif
But this works:
#ifdef audio
if(i==0){set_audio((char *)audio);return;}
#endif

You could do something like this:
#define audio audio
#define FF(X) #X
#define F(X) FF(X.c)
#ifdef audio
#include F(audio)
#endif
that is you'd have to append the .c before you place everything into a string. The usual concatenation "audio" ".c" -> "audio.c" of adjacent strings happens in a later compilation phase than preprocessing, so an #include directive cannot deal with this.

No. Preprocessor directives cannot be used like this. You can use macros to concatenate and stringify names, but that's another case. If you need this, you should most probably re-think your design because it's not good enough at the moment.

Maybe it's not clear to me... But I see a few different questions that you're asking...
I think your asking if you can include source files, yes you can, but its not the best idea; see here for a good discussion why.
If you're wondering about including files with "..." vs <...>, the difference is the quotes are when files are in your local directory (or you want to include the path to the file) the <> are for when the file is in your search path.
If you want to stringify the file name, then
Jens Guestedt answer is what you want... But I question the logic behind doing this...
Why not include the .c file in your project normally (add it to your makefile or whatever) then just wrap the code in question (or the while file) in the #ifdef? That's a much more standard way to conditionally compile the code.

Related

Switching between implementations in C precompiler

I'm fairly new to programming in C. My problem is that I have two implementations of a function and I want to be able to switch between them easily.
Right now I define the two implementations of the function as function_implementation1 and function_implementation1 in the files "funtion_implementation1.h" and "funtion_implementation2.h" respectively. To switch between them I have the following file:
#define IMPLEMENTATION1
#ifdef IMPLEMENTATION_1
#include "funtion_implementation1.h"
#define myFunction function_implementation1
#endif
#ifdef IMPLEMENTATION_2
#include "funtion_implementation2.h"
#define myFunction function_implementation2
#endif
In order to switch from one implementation to the other I just have to change the first line. This approach works, and I was satisfied with it for a while, but now it is bugging me that I have to open this file so often. I have a parameters.h file where I define all my parameters and I would rather choose which implementation to use in that file. Sadly, moving the first line to that file does not work. If I do that myFunction is not defined.
What is the best way to do this?
you should include your parameters file where you use alias, macros, etc:
#include "Parameters.h"
also, all your headers files should start with:
#ifndef __FILE_H__
#define __FILE_H__
// definitions go there
#endif
This prevents nested include of header files
Use preprocessor options, specifically the -D option. If you wanted to use IMPLEMENTATION1, when you are compiling that file on the command line (or in IDE), add -D IMPLEMENTATION1. This defines that macro. Same works for any macro

Write a macro for C/C++ #include

I work on AS/400 which is sometimes non-POSIX. We also need to compile our code on UNIX. We have an issue with something as simple as #include.
On AS/400, we need to write: #include "*LIBL/H/MYLIB"
On UNIX, we need to write #include "MYLIB.H"
At the moment we have this (ugly) block at the top of each C/C++ file:
#ifndef IS_AS400
#include "*LIBL/H/MYLIB"
/* others here */
#else
#include "MYLIB.H"
/* others here */
#endif
We would like a unified macro. Is this possible? I don't know how to write it.
Ideally, the resulting syntax would be: SAFE_INCLUDE("MYLIB") that would expand correctly on each platform.
Please advise.
You can simply #include some separate header in every of your source files containing that ugly #ifndef just once. It's a common practice anyway.
You can define prefixes for your platform as macro. Like
#define STRINGY(STR) #STR
#define SAFE_INCLUDE(HDR) STRINGY(HDR)
#ifndef IS_AS400
#define SAFE_INCLUDE(LIB) STRINGY(*LIBL/H/##LIB)
#else
#define SAFE_INCLUDE(LIB) STRINGY(LIB##.H)
#endif
and you can use this as
#include SAFE_INCLUDE(MYLIB)
There are two better solutions:
Use your Makefiles to properly set a path where compiler looks for includes.
For GCC you add to CFLAGS -I <path> (you can do that multiple times).
Wrap the non-compliant libraries with your own header files.

Pre-preprocessor

I want to have a C pre-preprocessor which is filtering some #define statements from the sourcecode without changing anything else.
Why? This should be used to remove some client specific code from the sources if the source is handed out to another client.
Does anyone know of an existing solution?
Thanks!
Simon
You can use something like awk instead of CPP ? Add some flags in your code surrounding the piece of code to be removed. For example:
(...)
//BEGIN_REMOVE_THIS_CODE
printf("secret code");
//END_REMOVE_THIS_CODE
(...)
then write a awk script to remove this code, something like...
BEGIN { write=1;}
/^\/\/BEGIN_REMOVE_THIS_CODE/ { write=0; next;}
/^\/\/END_REMOVE_THIS_CODE/ { write=1; next;}
{
if(write==1) print $0;
}
I recommend using an additional macro language layer for code filtering, like filepp. You may use a C preprocessor friendly syntax to express which parts belongs to which clients.
//%ifdef CLIENT_A
code for client A
//%endif
//%ifdef CLIENT_B
code for client B
//%endif
//%if "CLIENT_A" || "CLIENT_B"
code for client A and B
//%endif
The '//%' prefix enables You to compile the code unmodified. You may run filepp before You giving out the code to a client.
This sounds like what I asked about in Is there a C pre-processor which eliminates ifdef blocks based on values defined. The best answer I got was sunifdef, or 'Son of unifdef', which has worked reliably for me on some excessively contorted conditional code (the accumulated crud from over 20 years of development on a wide variety of platforms with an inadequate theory of how to do platform-specific compilation).
I don't think you need a preprocessor for this. If you don't have nested #ifdef's in your code, any regex engine can remove anything that is located between #ifdef CLIENT and #endif (use non-greedy matching to match first #endif, not last).
I would put the client specific code in a separate directory or possibly part of a different project that would need to be checked out of the source control.
Put a function call that would be stubbed out or (I forget the proper term) loosely linked so that another function can be put in its place.
If you're using gcc, then you can use:
gcc <insert files here> -E
The -E option tells gcc to only preprocess the sources, and not to compile them.
Or, you could use grep to filter out specific files and let the preprocessor loose on them only.
grep -r '#define CLIENT_CODE' ./*.h
You can also try unifdef which is rather simpler than sunifdef.
Why don't you do something like:
client_a_specific_functions_definition.c
double discount_for_paying_upfront() { return 0.1; };
// ...
client_b_specific_functions_definition.c
double discount_for_paying_upfront() { return 0.05; };
// ...
When you hand out the code it is just a matter of selecting the right file with their specific definitions.
Then you would create a header file to include it where you need to access the client specific code with something like:
client_functions.h
#pragma once
double discount_for_paying_upfront();
#define stringify(x) #x
#define FILE2(a) stringify(client_##a##_specific_functions_definition.c)
#define FILE(a) FILE2(a)
#include FILE(CLIENT_NAME)
#undef stringify
#undef FILE2
#undef FILE
Then say you #include "client_functions.h" in your main.c. You could compile it with:
gcc -DCLIENT_NAME=a main.c -o a.exe
gcc -DCLIENT_NAME=b main.c -o b.exe
as far as I know... the preprocessor can be run as a separate step (using the correct compiler optios) . This way you can do whatever you want with the processed code.

How can I keep doxygen from documenting #defines in a C file?

I have #define values in headers that I certainly want Doxygen to document but I have others in C files that I treat as static constants and I don't want Doxygen to document them. Something as simple and stupid as
#define NUMBER_OF(a) (sizeof((a))/sizeof((a)[0]))
#define MSTR(e) #e
How can I keep Doxygen from putting those #defines in the documentation it creates? I've tried marking it with #internal but that didn't seem to help.
A somewhat-related question on Doxygen and #define, how can I get:
#define SOME_CONSTANT 1234 /**< An explanation */
to put "SOME_CONSTANT" and "An explanation" but not "1234" in the output?
There is no need to use the \cond and \endcond commands. You can hide the initializer by simply using the \hideinitializer command:
#define SOME_CONSTANT 1234 /**< An explanation #hideinitializer */
Regarding the first question, you may set HIDE_UNDOC_MEMBERS = YES and only the macros having a Doxygen documentation block will be shown in the output.
You can set MAX_INITIALIZER_LINES = 0 in your doxyfile to hide the values of your defines.
You can exclude any part of code from Doxygen parsing with \cond ... \endcond tags.
edit: Some related questions:
How can Doxygen exclude a C++ class?
Exclude some classes from doxygen documentation
You only want to document what is declared in the .h files. I'm assuming you declare all static functions and variables as static in your .c files. All the remaining are declared in .h corresponding files also. These are your "public" members.
What I like to do in this case, and I believe doxygen was more designed to be used this way is:
in your Doxyfile, set EXTRACT_ALL = NO and add the directory where your .h files are to INPUT
add /** \file */ to all your .h files (but not your .c files).
This will index only what is contained in your .h files. You can still add the directory containing your .c files to INPUT at your Doxyfile, and they will be scanned for additional documentation for your "public" members...
It will no doubt still seem noisy and unnatural, but to address your other question, try:
/** An explanation */
#define SOME_CONSTANT /** #cond */ 1234 /** #endcond */
I solved this problem by moving my documentation from the .c file to the .h file. Then run doxygen only on the .h file.
Then the items that I want to document (the 'public' items) are intrinsically what doxygen picks up.
Because I have been previously careful to put 'public' items in the .h file and 'private' items in the .c file this works very well.
This technique came to mind when I noticed that doxygen was pulling in the includes. It struck me that if I were to also move the subset of includes that the calling module would need to use my module, then that list would be documented as well.
This technique has an additional benefit: I can put the documentation in one terminal window and the source in a different terminal window while updating the documentation.
Sometimes you may have a define which you want to document, but want doxygen to treat it differently (or even ignore it completely to avoid parsing errors).
For this you can define the #define in doxygen differently than in your sourcecode.
Example:
Some compilers allow variable linkage to specific segments, i.e.:
const int myvar # "segment_of_myvar_in_memory"=123;
=> doxygen would parse the "segment_of_myvar_in_memory" part as variable name which is not desired.
We could use a define for it:
#define __link_to_segment(name) # name
const int myvar __link_to_segment("segment_of_myvar_in_memory")=123;
If Preprocessing is active, Doxygen interprets our variable now as a function because of the function-like define using brackets..
But if we redefine our define within the Doxyfile, behaviour changes:
PREDEFINED = __link_to_segment(a)=
now the variable is parsed correctly as variable - also all types or keywords in front are correctly shown as keywords.
A nice side effekt:
In case you use 2 different IDEs with your code (one IDE for compiling&debugging, one for editing), you will also discover that some IDEs (i.e. Eclipse) have problems parsing variables with #"segment name". Using the approach above, you can redefine the __link_to_segment(name) there too:
#define __link_to_segment(name)
i.e. Eclipse will then show and parse the variable correctly, whereas the "compiling&debugging" IDE can still link the variable to its segment name.

Make the C preprocessor ignore certain #include directives

I use a parser generator here, that unfortunately insists on putting a
#include <some/file.h>
at the top of every generated source file. The header has since long been renamed. While it is no problem forcing the compiler (gcc) to use the new header with -include new/header.h, removing the above directive from every generated file complicates the build-process.
Is there a way to tell gcc to simply ignore some/file.h?
No. You can post-process your generated file - I say: NO!!!
Or you can just add '.' to your system include directories (or whatever your local include path is - make sure it's also a <> system include path).
Then make a 'some' directory and stick your own permanent 'file.h' in there that has 1 line for #include and get rid of your -include.
I'm guess there's some reason that might not work - cause it seems like the more straight forward and understandable thing to do before using -include. Especially since you can comment the pass-through file to explain what's going on.
Replace some/file.h with an empty file.
Why not make a symlink from some/file.h to new/header.h, and remove the -include directive?
Try using preprocessor directives like #if and #ifdef and gcc -DSYMBOL=value command line flag.
In example, if you compile using gcc -DREQUIRE_STDC=1 -o myfile.o myfile.c, and your .c file contains:
#if defined(REQUIRE_STDC) && defined(__STDC__)
#include "some/file.h"
#else
#include "another/file.h"
#endif /* defined(REQUIRE_STDC) && defined(__STDC__) */
It will compile using "some/file.h" if have both STDC and REQUIRE_STDC symbols defined. Also your header may include the proper directive to avoid multiple inclusions of the same file:
#ifndef MY_HEADER_FILE
#define MY_HEADER_FILE 1
/* your C declarations here */
#endif /* MY_HEADER_FILE */
Also, you could the gcc preprocessor manual.
#include <some/file.h>
may start as something like
#ifndef _FILE_H_
#define _FILE_H_
If so, just add #define _FILE_H_ before the #include command and it should ignore it.
I'm not sure whether this is the best solution, though.

Resources