Declaring the Unix flavour in C/C++ - c++

How do I declare in C/C++ that the code that is written is to be built in either HP-UX or Solaris or AIX?

I found that, a good way to figure this king of question, is, at least with gcc, to have this makefile:
defs:
g++ -E -dM - < /dev/null
then, :
$ make defs
should output all the definitions you have available.
So:
$ make defs | grep -i AIX
$ make defs | grep -i HP
should give you the answer. Example for Linux:
$ make defs | grep -i LINUX
#define __linux 1
#define __linux__ 1
#define __gnu_linux__ 1
#define linux 1
Once you found the define you are looking for, you type at the beginning of your code:
#if !(defined(HP_DEFINE) || defined(AIX_DEFINE) || defined(SOLARIS_DEFINE))
# error This file cannot be compiled for your plateform
#endif

How about a macro passed to the compiler ?
i.e. gcc -Dmacro[=defn]
Then test for the macro in your code with a simple #ifdef of #if (if you've given it a value). There may already be a predefined macro for your target platform as well.
[EDIT: Put some of my comments here in my answer that explain how -D works]
-Dmacro[=defn] on the command line for the compiler is the same as having #define macro defn in the code. You expand it out like this: -Dfoo=bar is equivalent to #define foo bar. Also, the definition is optional so -Dfoo is equivalent to #define foo.

Be careful about how you handle this. You should identify the features of the O/S that you want to use by feature, not by O/S, and write your code accordingly. Then, in one header, you can identify which of the features are available on the O/S that you are compiling on. This is the technique used by autoconf, and even if you do not use autoconf itself, the technique it espouses is better than the platform-based technique. Remember, the features found on one O/S often migrate and become available on others too, so if you work by features, you can adapt to the future more easily than if you work solely on the O/S.
You also have to write your code appropriately, and portably. Isolate the O/S dependencies in separate files whenever possible, and code to an abstract O/S interface that does what you need. Taken to an extreme, you end up with a Java JVM; you don't need to go that far, but you can obviate most of the problems.
Take a look at portable libraries like the Apache Portable Runtime (APR) library.
And write your code along the lines of:
#ifdef HAVE_PWRITE
...code using pread() and pwrite()...
#else
...code using plain old read() and write()...
#endif
This is a grossly over-simplified example - there could be a number of fallbacks before you use plain read() and write(). Nevertheless, this is the concept used in the most portable code - things like GCC and Apache and so on.

Perhaps a less convoluted solution that some of those suggested is to consult Pre-defined C/C++ Compiler Macros. This site provides an extensive list of compiler macros for a large number of compiler/OS/Architecture combinations.

Related

Exclude parts from compilation - still syntax-check

We have a pretty large project here in C++/.NET/Visual Studio, for performance testing we incuded some code that makes it possible to evaluate the execution time between certain points.
PERFORMANCE_TEST BeginMeasureTime("execute someCode")
someCode
PERFORMANCE_TEST EndMeasureTime("execute someCode")
Usually while developing the PERFORMANCE_TEST macro would be set to // so the evaluation code is switched off. So if code / interfaces etc. change and the code after the PERFORMANCE_TEST macro becomes invalid, the developer will not notice that.
Is there any smarter way to have the performance evaluation code only built in a special version of the project but still make sure that it stays consistent? How would you normally do something like that?
One easy way would be to change
PERFORMANCE_TEST xxx
to
PERFORMANCE_TEST(xxx)
Then instead of
#if PERFORMANCE_TEST_ENABLED
#define PERFORMANCE_TEST
#else
#define PERFORMANCE_TEST //
#endif
you could have
#if PERFORMANCE_TEST_ENABLED
#define PERFORMANCE_TEST(x) {x;}
#else
#define PERFORMANCE_TEST(x) if(0) { x; }
#endif
An optimizing compiler should generate no code for the second version if performance tests are disabled (or at the very least it'll not branch on the if), but it'll still be part of the compilation.
Alternatively, if build times aren't a huge concern you could simply always build both versions into separate directories.
It's been a while since I did something like this the following should be what you want. If the MACRO is defined then the function is included, else it the function is a noop and compiled out the code.
#ifdef MACRO
#define MACRO_NAME(arg1, arg2, ...) [code to expand to]
#else
#define MACRO_NAME(arg1, arg2, ...) noop
#endif
Update:
Ok so I slightly got the question a bit incorrect.
Most static analysis tools can be configured to scan certain #defines
CPPCheck for example can be given the following arguments.
-D<ID> Define preprocessor symbol. Unless --max-configs or
--force is used, Cppcheck will only check the given
configuration when -D is used.
Example: '-DDEBUG=1 -D__cplusplus'.
So you can then scan the code twice, thus achieving your goal.
I would say this is the best of both before you can add more scans if you add more #define
Or you can use some of the following to scan more configurations.
-f, --force Force checking of all configurations in files. If used
together with '--max-configs=', the last option is the
one that is effective.
and
--max-configs=<limit>
Maximum number of configurations to check in a file
before skipping it. Default is '12'. If used together
with '--force', the last option is the one that is
effective.
We used this type of operation at a previous company, we build code for WIN32, Pocket PC and WM5 and WM6 all from the same code base but had static checking on all build configurations. But the end result was the removal of non redundant code in all builds.

How do I strip out inactive #if directives with the gcc/g++ preprocessor?

I am using a third party open source project and need to strip out the inactive #ifs, #ifdefs, etc to better understand the code flow.
Is there a way to use make to produce versions of the source files without these directives? I'd like to avoid expanding macros, just remove directives.
I was looking at
https://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html
and it seems like -dD and -fdirectives-only are good options to start.
Where will these preprocessed files appear? Where do I add these commands for use with a Makefile and "make"?
I tried running "make -n" to produce a script and adding options to the g++ and gcc calls in the script after -Wformat among other things, but I dont notice anything.
I'm not sure if this complicates anything, but I am also using avr-gcc and avr-g++.
I have looked at coan, which does not support #included #defines so it would not work for this purpose, and I could not get sunifdef to work. Is there is a way of doing this with the preprocessor.
The defines are scattered among the current file, the included files, and included makefiles that specify -Dfoo=opt options.
You're on the right track with your preprocessor options. -D will define a macro with a value of 1, -U will cancel any previous definition (it will become undefined), and -fdirectives-only will suppress macro expansion. In addition to those, you can use the -E flag with gcc to tell it to provide the preprocessor output as separate files for your examination. However, I don't think they're going to be quite what you expect. The CPP (C pre-processor) output may have other things added to it, as suggested by this SO question, and you should check the gnu CPP output manual page. That is what you will get from the CPP.
It sounds like you want to be able to strip this extraneous code once and develop from there. To do that, I would encourage you to give unifdef another try. This is what unifdef was designed to do, while the CPP was designed to prepare code for compilation. They're different tasks, so you should use the right tools for them. It is available as a standalone application at http://dotat.at/prog/unifdef/ and is built into some Linux Shells.
It allows you to specify macros that you want it to consider defined or undefined, and it removes blocks of code where the conditional directive would evaluate to false. For example, you can run it like this:
unifdef -I< path > -DMACRO1 -UMACRO2
It will search through the directory specified by < path > through C/C++ source files, looking for #if, #ifdef, #ifndef, etc. When it encounters them, it will evaluate the conditional expression and selectively remove the code controlled by that expression. Consider an input file with this code:
int i = 0;
#ifdef MACRO1
int j = 0;
#endif /* ifdef MACRO1 */
int k = 0;
int m = 0;
#if (MACRO1 && MACRO2)
int n = 0;
#endif /* if (MACRO1 && MACRO2) */
int p = 0;
int q = 0;
#ifdef MACRO3
int r = 0;
#endif /* ifdef MACRO3 */
int t = 0;
If we call unifdef like my example above, the output will be this:
int i = 0;
int j = 0;
int k = 0;
int m = 0;
int p = 0;
int q = 0;
#ifdef MACRO3
int r = 0;
#endif /* ifdef MACRO3 */
int t = 0;
Notice that the declaration of n has been removed, because it was contained in a preprocessor #if/#endif block whose controlling expression evaluated to false (we told unifdef to consider MACRO2 undefined). The declaration of j remains, but the #ifdef and #endif statements were removed because the controlling expression was known to be true.
The block that depends on MACRO3 is left untouched because its state is unknown.
There is a significant amount of flexibility and control over how this runs, too.
If you decided you do want it to be part of your build process, you can always add it to your makefile.
If you do not have a list of which macros should be defined or undefined available, you can use the "unifdefall" script provided with unifdef and it will use the CPP to discover macro definitions in the source code on its own, and remove/keep code blocks according to the definitions contained in the source code.
TL;DR
Yes you can (sort of) do it with the preprocessor. But unifdef and sunifdef are tools that are made to do exactly this, so you should use them instead.
Assumptions
The aim of the exercise is to produce a body of C/C++ source code with most of the conditional compilation removed, and which compiles to the identical binaries.
This is third party source code, and you are aware of the problems of merging subsequent updates.
This is open source, but you have no intention of ever distributing modified source code.
The programs are arbitrarily complex and are built by arbitrarily complex makefiles or similar tools, with command-line symbol definitions and/or configuration include files.
My strategy is to use a program like unifdef. The first time I did this I wrote my own, and you may have to modify the program to produce the desired results.
The core strategy is:
Identify a single likely defined symbol (experimentation or trial and error required).
Run the code through unifdef.
Optionally, compare before and after source visually to spot obvious problems.
Build the after version to ensure it builds correctly.
Compile the before and after versions to produce pre-processed output using the same makefiles.
Compare pairs of before and after pre-processed source. They should be identical, give or take some white space.
Resolve issues by editing either before or after version as required.
Optionally, remove all references to the symbol from all makefiles. [It should make no difference.]
Repeat, using the after version and a different symbol.
One symbol at a time, testing thoroughly every time. Some symbols may turn out to be too hard, and if you have much more than a million lines of source code and a hundred or so symbols it can all get out of hand.
Final step: if you modify unifdef then feel free to contribute your changes back to the community. This is a seriously challenging task to do well!
Use make -n to create the shell script produced by the makefile.
Go to the line where it runs avr-g++ and add -dM -E before all the rest of the options.
Go to the file after the -o and the list of #defines will be there (it should probably be something.o)
Use unifdef -f definesFile.o filename

Pass directory to C++ application from compiler

Some applications contain scripts that are run by the main application that reside in /usr/libexec. However, the autoconf scripts are able to change that directory by passing --libexecdir to the configure script.
For example, when running ./configure in the git source code, I can set --libexecdir to any directory I want, and the program will still work.
What do I need to add to a C++ to make this functionality work? In other words, how can I have a directory name set by a configure script compiled into the program?
You need the value of the #libexecdir# substitution variable (as used in e.g. Makefile.in) to be exposed to your C++ code. The simplest and most reliable way to do that is with a -D switch on the compiler command line for the object file that needs to know:
foo.o: CPPFLAGS += -DLIBEXECDIR='"$(libexecdir)"'
In foo.cc, LIBEXECDIR will then be a preprocessor macro expanding to a string constant that has the path you need. Two caveats, though: The above Makefile snippet uses a GNU make feature, target-specific variables. It will not work in other Make implementations. Also, I didn't bother quoting any characters in the expansion of $(libexecdir). Fully defensive quoting would look something like this:
foo.o: CPPFLAGS += \
-DLIBEXECDIR='"$(subst ",\",$(subst ','\'',$(subst \,\\,$(libexecdir))))"'
You will definitely need at least the innermost $(subst ...) construct if you want to be able to use Windows pathnames, with the slashes going the wrong way. People don't usually put ' or " in pathnames, so I probably wouldn't bother with the outer two until someone complained.
The same technique will work for any #whatever# substitution variable that isn't also an AC_DEFINE.
You might think you could use AC_DEFINE_UNQUOTED somehow to get the value of $(libexecdir) into config.h and so avoid all this mucking around with the command line. Unfortunately, Autoconf doesn't fully compute the value of its #*dir# substitutions at configure time:
# near the top of the generated 'configure':
exec_prefix=NONE
libexecdir='${exec_prefix}/libexec'
# much, much later -- as part of AC_OUTPUT:
test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
Therefore, if you do the obvious thing with AC_DEFINE_UNQUOTED, you will get something like
#define LIBEXECDIR "${exec_prefix}/libexec"
in your config.h. So that's not going to work, and I don't see a good way to make it work.

Any utility to test expand C/C++ #define macros?

It seems I often spend way too much time trying to get a #define macro to do exactly what i want. I'll post my current dilemma below and any help is appreciated. But really the bigger question is whether there is any utility someone could recommend, to quickly display what a macro is actually doing? It seems like even the slow trial and error process would go much faster if I could see what is wrong.
Currently, I'm dynamically loading a long list of functions from a DLL I made. The way I've set things up, the function pointers have the same nanes as the exported functions, and the typedef(s) used to prototype them have the same names, but with a prepended underscore. So I want to use a define to simplify assignments of a long long list of function pointers.
For example, In the code statement below, 'hexdump' is the name of a typedef'd function point, and is also the name of the function, while _hexdump is the name of the typedef. If GetProcAddress() fails, a failure counter in incremented.
if (!(hexdump = (_hexdump)GetProcAddress(h, "hexdump"))) --iFail;
So let's say I'd like to replace each line like the above with a macro, like this...
GETADDR_FOR(hexdump )
Well this is the best I've come up with so far. It doesn't work (my // comment is just to prevent text formatting in the message)...
// #define GETADDR_FOR(a) if (!(a = (#_#a)GetProcAddress(h, "/""#a"/""))) --iFail;
And again, while I'd APPRECIATE an insight into what silly mistake I've made, it would make my day to have a utility that would show me the error of my ways, by simply plugging in my macro.
Go to https://godbolt.org/. Enter your code in the left pane and select compiler as gcc put the argument as -E in the right pane. Your pre-processed code will appear on the right.
You can just run your code through the preprocessor, which will show you what it will be expanded into (or spit out errors as necessary):
$ cat a.c
#define GETADDR_FOR(a) if (!(a = (#_#a)GetProcAddress(h, "/""#a"/"")))
GETADDR_FOR(hexdump)
$ gcc -E a.c
# 1 "a.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "a.c"
a.c:1:36: error: '#' is not followed by a macro parameter
GETADDR_FOR(hexdump)
In GCC, it's gcc -E foo.c to only preprocess the file.
Visual Studio uses the /P argument.
http://visualstudiogallery.msdn.microsoft.com/59a2438f-ba4a-4945-a407-a1a295598088 - visual studio plugin to expand macroses
You appear to be confused about what the exact syntax is for stringifying or token pasting in C preprocessor macros.
You might find this page about C preprocessor macros in general helpful.
In particular, I think this macro should read like this:
#define GETADDR_FOR(a) if (!(a = (_##a)GetProcAddress(h, #a))) --iFail
The trailing ; should be skipped because you will likely be typing this as GETADDR_FOR(hexdump);, and if you don't it will look very strange in your C code and confuse many syntax highlighters.
And as someone else mentioned gcc -E will run the preprocessor and skip the other compilation steps. This is useful for debugging preprocessor problems.
You might want to take a look at Boost Wave. Like most of Boost, it's really more a library than a utility, but it does have a driver to act as a complete preprocessor.

Is there a C pre-processor which eliminates #ifdef blocks based on values defined/undefined?

Original Question
What I'd like is not a standard C pre-processor, but a variation on it which would accept from somewhere - probably the command line via -DNAME1 and -UNAME2 options - a specification of which macros are defined, and would then eliminate dead code.
It may be easier to understand what I'm after with some examples:
#ifdef NAME1
#define ALBUQUERQUE "ambidextrous"
#else
#define PHANTASMAGORIA "ghostly"
#endif
If the command were run with '-DNAME1', the output would be:
#define ALBUQUERQUE "ambidextrous"
If the command were run with '-UNAME1', the output would be:
#define PHANTASMAGORIA "ghostly"
If the command were run with neither option, the output would be the same as the input.
This is a simple case - I'd be hoping that the code could handle more complex cases too.
To illustrate with a real-world but still simple example:
#ifdef USE_VOID
#ifdef PLATFORM1
#define VOID void
#else
#undef VOID
typedef void VOID;
#endif /* PLATFORM1 */
typedef void * VOIDPTR;
#else
typedef mint VOID;
typedef char * VOIDPTR;
#endif /* USE_VOID */
I'd like to run the command with -DUSE_VOID -UPLATFORM1 and get the output:
#undef VOID
typedef void VOID;
typedef void * VOIDPTR;
Another example:
#ifndef DOUBLEPAD
#if (defined NT) || (defined OLDUNIX)
#define DOUBLEPAD 8
#else
#define DOUBLEPAD 0
#endif /* NT */
#endif /* !DOUBLEPAD */
Ideally, I'd like to run with -UOLDUNIX and get the output:
#ifndef DOUBLEPAD
#if (defined NT)
#define DOUBLEPAD 8
#else
#define DOUBLEPAD 0
#endif /* NT */
#endif /* !DOUBLEPAD */
This may be pushing my luck!
Motivation: large, ancient code base with lots of conditional code. Many of the conditions no longer apply - the OLDUNIX platform, for example, is no longer made and no longer supported, so there is no need to have references to it in the code. Other conditions are always true. For example, features are added with conditional compilation so that a single version of the code can be used for both older versions of the software where the feature is not available and newer versions where it is available (more or less). Eventually, the old versions without the feature are no longer supported - everything uses the feature - so the condition on whether the feature is present or not should be removed, and the 'when feature is absent' code should be removed too. I'd like to have a tool to do the job automatically because it will be faster and more reliable than doing it manually (which is rather critical when the code base includes 21,500 source files).
(A really clever version of the tool might read #include'd files to determine whether the control macros - those specified by -D or -U on the command line - are defined in those files. I'm not sure whether that's truly helpful except as a backup diagnostic. Whatever else it does, though, the pseudo-pre-processor must not expand macros or include files verbatim. The output must be source similar to, but usually simpler than, the input code.)
Status Report (one year later)
After a year of use, I am very happy with 'sunifdef' recommended by the selected answer. It hasn't made a mistake yet, and I don't expect it to. The only quibble I have with it is stylistic. Given an input such as:
#if (defined(A) && defined(B)) || defined(C) || (defined(D) && defined(E))
and run with '-UC' (C is never defined), the output is:
#if defined(A) && defined(B) || defined(D) && defined(E)
This is technically correct because '&&' binds tighter than '||', but it is an open invitation to confusion. I would much prefer it to include parentheses around the sets of '&&' conditions, as in the original:
#if (defined(A) && defined(B)) || (defined(D) && defined(E))
However, given the obscurity of some of the code I have to work with, for that to be the biggest nit-pick is a strong compliment; it is valuable tool to me.
The New Kid on the Block
Having checked the URL for inclusion in the information above, I see that (as predicted) there is an new program called Coan that is the successor to 'sunifdef'. It is available on SourceForge and has been since January 2010. I'll be checking it out...further reports later this year, or maybe next year, or sometime, or never.
I know absolutely nothing about C, but it sounds like you are looking for something like unifdef. Note that it hasn't been updated since 2000, but there is a successor called "Son of unifdef" (sunifdef).
Also you can try this tool http://coan2.sourceforge.net/
something like this will remove ifdef blocks:
coan source -UYOUR_FLAG --filter c,h --recurse YourSourceTree
I used unifdef years ago for just the sort of problem you describe, and it worked fine. Even if it hasn't been updated since 2000, the syntax of preprocessor ifdefs hasn't changed materially since then, so I expect it will still do what you want. I suppose there might be some compile problems, although the packages appear recent.
I've never used sunifdef, so I can't comment on it directly.
Around 2004 I wrote a tool that did exactly what you are looking for. I never got around to distributing the tool, but the code can be found here:
http://casey.dnsalias.org/exifdef-0.2.zip (that's a dsl link)
It's about 1.7k lines and implements enough of the C grammar to parse preprocessor statements, comments, and strings using bison and flex.
If you need something similar to a preprocessor, the flexible solution is Wave (from boost). It's a library designed to build C-preprocessor-like tools (including such things as C++03 and C++0x preprocessors). As it's a library, you can hook into its input and output code.