C/C++ preprocessor #if with datetime - c-preprocessor

I guess this is not possible (yet) but not sure. I need to do conditional compilation based on current date. Something like:
#if (__CURRENT_YEAR < 2016)
...
#endif
I need to exclude something from project after some months and be sure that this will not be forgotten (in future releases).

In your Makefile add
CFLAGS += -DYEAR=$(shell date +%g)
Then in your C source:
#if (YEAR < 16)
....
#endif

Something like this isn't possible with the C preprocessor, but could be solved at a higher level via your build system. You could build some scripting that would auto-generate a header at build time that contains something like:
#define __CURRENT_YEAR 2015
This header would then be included by your code that is date-sensitive. Depending upon the implementation of your build system, you could do this automatically at each build or if a year change is detected.

Related

How can I compile two version of my code in IAR Embbedded Workbench

I have two version of code and I need to switch them as work need to compile each one while keeping two version on an IAR project. I find something like "compile switch" but I don't know how is it doing. Is there anyone tell me a keyword or an advice that can I search?
You can use C preprocessor #define feature to toggle between code versions and use IAR EWARM project's Defined Symbols feature to enable a list of #defines in a specific header file (for example: defines.h) that will be included in all C files.
defines.h
#if defined(PROD_VERSION)
#define SOFTWARE_VERSION_PRODUCT ("1.0-release")
//...whetever specific #defines meant for the release version, for example...
//#define ENABLE_RF_STUB
#define USE_SERIAL_CTS_RTS
#elif defined(TEST_VERSION)
#define SOFTWARE_VERSION_PRODUCT ("1.0-test")
//...whetever specific #defines meant for the test version, for example...
#define ENABLE_RF_STUB
#define USE_SERIAL_CTS_RTS
#elif defined(DEBUG_VERSION)
#define SOFTWARE_VERSION_PRODUCT ("1.0-debug")
//...whetever specific #defines meant for the debug version, for example...
#define ENABLE_RF_STUB
//#define USE_SERIAL_CTS_RTS
#endif
in rf.c
#include "defines.h"
void rfInit(void)
{
#ifndef ENABLE_RF_STUB
//init RF here
#endif
}
In serial.c
#include "defines.h"
CPU_BOOLEAN isCtsRts()
{
#ifdef USE_SERIAL_CTS_RTS
return HAL_SERIAL.isCtsRts();
#else
return DEF_TRUE; //bypass CtsRts check
#endif
}
In your project option > C/C++ Compiler > Preprocessor > Defined symbols: add PROD_VERSION if you want the release version, or add TEST_VERSION if you want the test version or add DEBUG_VERSION if you want the debug version.
You can only choose one of the three configurations above only as IAR will only compile one version via the project compilation. Unless you can create a batch build script to allow building all the three versions under different output files created with three different project setups.
IAR has a configuration in toolbar Project > Edit_Configuration
It makes you set version "switches" via set these tool and it is possible to set preprocessor command for each setup.

c preprocessor to determine project or exe name

I have a C resource file called resources.rc, which contains the following line to specify the icon used for a project
1000 ICON "icon222.ico"
I would like to use this same resource file for several projects using
a pre processor conditional depending on the project..
e.g
#if __PROJECT__ == "myapp.exe"
1000 ICON "icon222.ico"
#endif
#if __PROJECT__ == "myotherapp.exe"
1000 ICON "icon777.ico"
#endif
Is there a standard C macro or definition that could be used to
achieve something like this ?
As far as I known there is no predefined macro carring a project specific value setup by VC.
So just select one yourself like MYPROJECTNAME and #define it differently in each of your projects and then do test this in your rc file as by your posting.
I'm not sure anymore whether VC uses the pre-processor on the rc file automagically or if you need to apply some mods to VC's build process to have it do this.
Update:
To have this feature added using ${EXENAME} in terms of having global (solition wide) settings for VC a way to go might be shown here: Visual c++ 2008: how to have global settings defined in a solution or/and here: Can I pass a preprocessor definition to the resource compiler through the command line?

Eclipse and C based issue: #defines aren't working outside of header files

Using Eclipse IDE. Problem is that #defines aren't passing from the headers to the c and h files. Not sure if it's a project settings thing or what, but Visual Studio IDE is not giving me any trouble on the same project. Some of the projects in Eclipse don't have this problem though. Any ideas on what may be wrong? See example of the problem below.
Even though EXAMPLE is defined in header1.h, it is not recognized as defined in main.c. There is no issue with the compiler finding the headers either. Thanks for the help all.
Header1.h
#define EXAMPLE 1
main.c
#include "Header1.h"
#if defined(EXAMPLE)
/* code here */
#endif
You mention there is no issue with the compiler and visual studio, so assuming you are referring to the code being grayed out in the Eclipse IDE? If so, check the Indexer settings
Preferences --> C/C++ --> Indexer
Check Enable Indexer Check Index Source files not included in the
build Check Automatically update the index Check Use Active build
Configuration
etc,...
hope this was relevant to your issue.
Does this work?
#ifdef EXAMPLE
instead of
#if defined(EXAMPLE)
Behavior similar to that in the question can be seen when using #defines that are strings, not integers.
The following code seems like it should run Code(); only when MODE is equal to the string different:
mode.h
#define MODE something
different.cpp
#include "mode.h"
#if MODE == different
Code();
#endif
Eclipse shows Code(); as being active when it appears it should be inactive. The reason for this is that the preprocessor does not support string comparisons, only integer ones1.
When mousing over MODE in different.cpp, MODE is shown as having the value something. Although this is technically correct, it can be misleading since both MODE and something evaluate to the same thing (a defined but empty value). Given that they both have the same value (nothing) they evaluate as being equal and Code(); is run.
1 This is gone into in more detail in this question.
Solutions
Two possible ways of correctly handling this come to mind:
Assign numeric values to each option
Use unique #defines for each option
Use numeric values
The code could be written as follows:
mode.h
#define MODE_something 0
#define MODE_different 1
#define MODE MODE_something
different.cpp
#include "mode.h"
#if MODE == MODE_different
Code();
#endif
In this case the code works as expected since MODE and MODE_different evaluate to two distinct values (0 and 1, respectively).
Use unique #defines
Another approach is to use uniquely-named macros for each option. For example:
mode.h
// Select the active mode:
#define MODE_something
//#define MODE_different
different.cpp
#include "mode.h"
#ifdef MODE_different
Code();
#endif

Processing some directives leaving others

I use to go through C code having lot of #ifdef, #if and #endif directive which keep some portion active and some portion inactive depending on some variables are defined or not. I searched for something that can process them to generate final C code. But the preprocessing also does the same for #include and #define. But I want to keep them.
So, is there any thing to preprocess these files or project with some filtering?
There are a series of programs that can do that:
unifdef - the oldest
sunifdef (Son of Unifdef)
coan (Son of sunifdef)
I've used sunifdef extensively on some very contorted code and have never found it to make a mistake. I'm ready to start using coan now, though it will still be under scrutiny for a while. Version 4.2.2 was released today, 2010-12-20.
See also: SO 525283
I assume you're using gcc.
If you mean all #includes, I think you need to remove them, expand the resulting file with gcc -E then add the #includess back.
If you mean only the standard headers, the option -nostdinc may help you do what you want
user#host:~/test/tmp$ cat 4437465.c
#include <stdio.h>
#ifndef OUTPUT_TYPE
#define OUTPUT_TYPE 1
#endif
int main(void) {
#if OUTPUT_TYPE == 1
printf("output type 1\n");
#elif OUTPUT_TYPE == 2
printf("output type 2\n");
#else
printf("default output type\n");
#endif
return 0;
}
user#host:~/test/tmp$ gcc -DOUTPUT_TYPE=2 -nostdinc -E 4437465.c
# 1 "4437465.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "4437465.c"
4437465.c:1:19: error: no include path in which to search for stdio.h
int main(void) {
printf("output type 2\n");
return 0;
}
what you want might be actually a bad idea, as there might be definitions coming from included files, describing your architecture, for example... But any modern IDE can visualize the #if preprocessor directives.
We used a custom parser to achieve what you intend to do. Lex & YACC
would be a good start for such tool.
On a side note, it was a really painful way to manage different versions of binaries in a large code base. If it's possible, try to isolate your optionnal code parts in different libraries that can or cannot be included in your final deliverable as a dynamic or static library.

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.

Resources