Lets say there is this code:
#ifndef TEST_H_
#define TEST_H_
#define NAME "John Doe"
#endif
The definition NAME is used in one of the .c files
void print_name()
{
printf("Name is: %s\n\n",NAME)
}
Is it possible to compile the program.. then change the value of NAME to "Johnny" and when the program is run again.. without compiling it, It prints "Johnny" instead of "John Doe"??
I am just curious to know if it is possible.
Thanks for any help or advice..
Not trivially. Included files get pasted into the source and the source nor the headers no longer technically exist in the binary output.
You can however edit the binary, and if you do it right (e.g., can't replace a 10-character string with a 3-character replacement as that'd misalign stuff), you can get it to work.
Example: (your example simplified):
#include <stdio.h>
int main()
{
printf("Name is: %s\n\n","John Doe");
}
Compile, run, edit, re-run:
$ gcc file.c
$ ./a.out
Name is: John Doe
$ sed -i 's/John Doe/Johnny\x00\x00/' a.out
$ ./a.out
Name is: Johnny
That depends on what you mean by not re-compiling. You need to change the program file somehow, but you can do that in various ways:
A hex editor other "direct" modification of the executable file, where you can look for the string "John Doe" and replace it with "Johny" (with extra null-byte padding), as described by PSkocik and MustacheMoses
Depending on the modification, I am fairly sure there are more specialized tools for attempting them. I don't know what they are, though.
You could also make NAME be an extern variable instead of a macro, with extern char *NAME; in a header file and char *NAME = "John Doe"; in a separate .c file. Then if you want to change the name, you just need to change it in the one, small, file where it's defined, re-compile that, and then just re-link with the rest of the program. That still involves some re-compiling, but it's a lot faster than re-compiling everything.
To make a recommendation I'd need to know your use case, but the third option I mention is a lot more common than just modifying an executable file directly.
Yes you can use something called a hex editor to change the contents of stored strings in the generated executable.
A macro is something that cannot change without recompiling again. It's not a variable or something you can operate on, so it's imposible to make a macro to give a different value than programmed, but to change the value and recompile.
You can give the macro different definitions, based on the value of another macro (one that you can pass the compiler on the command line when compiling) but anyway, you need to recompile the source again. This allows you to tweak the file without having to edit it, but never avoids you to recompile it again.
source.c
#include <stdio.h>
#ifndef VERSION
#define VERSION 0
#endif /* VERSION */
#if VERSION
#define NAME "John Doe"
#else
#define NAME "Johnny Guitar"
#endif
int main()
{
puts("the winner is " NAME);
} /* main */
that you can compile with
$ cc source.c
$ a.out
the winner is Johnny Guitar
$ _
or
$ cc -DVERSION=1 source.c
$ a.out
the winner is John Doe
$ -
It is possible if the program opens the header file, scans to find #define NAME line, then gets the value. Something like very simple preprocessor. And if you add #if or #ifdef conditions, the final value may be invalid.
Not. Definitions are part of the preprocessor and aren't not the C variables and symbols. During the preprocessing definitions are textually replaced by their values
If you need to change something during the program execution you need the C variable
char NAME[] = "John Doe";
And you are done
Related
I write a framework with lot of function that are named like that :
ICE_ModuleType_FunctionUse()
and everything else have ICE_ prefix (typename, define etc...)
And with preprocessor I would like to remove ICE_ to reduce function name lenght when the user know there is no conflict with other libs.
But the only working way I found was to write every function, type etc... by hand like that :
#define ModuleType_FunctionUse ICE_ModuleType_FunctionUse
Any Idea on how to easly do that ?
You could automatically create a new header file with a name like use_namespace_ICE.h for your clients to use. This file would have the required list of #defines, and can be generated using the utilities nm or dumpbin applied to your library.
For example, if foo.c is:
void ICE_ModuleType_FunctionUse(void) { /* code */ }
then:
cc -c -o foo.o foo.c
nm foo.o | grep ' T _ICE_' | sed 's/.* T _ICE_\(.*\)/#define \1 ICE_\1/'
yields:
#define ModuleType_FunctionUse ICE_ModuleType_FunctionUse
As the comments tell you, there is no way, or no easy way, to shorten identifiers once written in your source code. However, you can reduce the typing for things that still need to be written:
#define ModuleType_FunctionUse ICE_ModuleType_FunctionUse
This defines that the short name will be replaced with the longer name.
If I do this below:
#include <stdio.h>
int main()
{
printf ("%s\n",__FILE__);
return 0;
}
>gcc cfilename.c
>./a.out
>cfilename.c
>pwd
>/home/tek/cpp
> gcc -v
> gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)
only file name is printed, I think it should print it with complete path, google search tells me people asking help to get only file name?
The ISO C standard (currently C11) has this to say about the content of the __FILE__ predefined macro:
__FILE__: The presumed name of the current source file (a character string literal).
And that's about it. There is no mandate on the format of the content so I suspect a implementation could probably get away with setting it to "some file I found in the /src tree" and still claim conformance.
So it's basically up to the implementation as to what it puts in there. You'll need to investigate specific implementations to see how they handle it. The gcc compiler, for example, uses the file exactly as you specified on the command line so, if you want the full path, it's the command line you'll have to change, something like:
gcc -o myexec $(pwd)/myexec.c
It's interesting to note that gcc seems to do the opposite for included files. When you use:
#include "myheader.h"
the __FILE__ macro is set to the full expansion of the header file.
If you have an implementation that doesn't set __FILE__ in the manner you need, there's nothing stopping you from creating your own with something like:
dodgycc -o myexec -DMY_FILE_NAME=$(pwd)/myexec.c myexec.c
(where the -D option of the dodgycc compiler defines a preprocessor token to be what you need).
I have a program which, depending on the user input, #includes one header headerA.h or another headerB.h I expect the header to be there till the end of the program.
headerA and headerB define structures with the same names but with different fields, and I'm not able to merge both files in one, and neither able to change anything else from the libraries that headerA and headerB are using.
Is there a way to solve this problem?
Preprocessor macros:
#if defined(USE_HEADERA)
# include "headerA.h"
#elif defined(USE_HEADERB)
# include "headerB.h"
#else
# error must define USE_HEADERA or USE_HEADERB
#endif
If you have GCC then you tell the preprocessor which to select using the GCC -D option:
$ gcc -DUSE_HEADERA myfile.c -o myprogram
However, if you want to do it runtime during execution that's impossible. #include is a preprocessor directive, and the preprocessor only runs as part of the compilation.
Although it is possible to conditionally include files, it does not seem to be possible to have this change during runtime. See this answer about it. The if statements only work before runtime.
I don't think it is possible as your #includes are resolved before compilation i.e during preprocessing. So it is not possible to change them during runtime.
But you can try conditional compilation by defining a macro during compiletime.
#ifdef HEADERA
#include <headerA>
#ifdef HEADERB
#include <headerA>
While compilinging gcc
$ gcc prog.c -DHEADERA to include headerA or vice versa
In ruby there's very common idiom to check if current file is "main" file:
if __FILE__ == $0
# do something here (usually run unit tests)
end
I'd like to do something similar in C after reading gcc documentation I've figured that it should work like this:
#if __FILE__ == __BASE_FILE__
// Do stuff
#endif
the only problem is after I try this:
$ gcc src/bitmap_index.c -std=c99 -lm && ./a.out
src/bitmap_index.c:173:1: error: token ""src/bitmap_index.c"" is not valid in preprocessor expressions
Am I using #if wrong?
As summary for future guests:
You cannot compare string using #if
BASE_FILE is the name of file that is being compiled (that Is actually what I wanted).
Best way to do this is to set flag during compilation with -D
in gcc you can use:
#if __INCLUDE_LEVEL__ == 0
or:
if(!__INCLUDE_LEVEL__)
to check if your inside the __BASE_FILE__
Yes, you are misusing #if. It only works on integer constant expressions. But even if you were using if, comparing pointers for equality is never a valid way to compare strings in C.
It seems you can't.
Alternatively, it works perfectly fine on a regular if condition, and gcc can optimize this nicely.
if (!strcmp(__BASE_FILE__, __FILE__)) {
// works.
}
but you can't define new main functions or use other preprocessor tricks. but you could short-circuit main by using static methods, but that's harsh and dirty.
But maybe you shouldn't do it. in Ruby/python, this works because usage of files is done at runtime. in C, all files are to be compiled to be used.
Keep in mind that most build system will build one file at a time, building them as object files, and rebuilding them only when necessary. So
__BASE_FILE__ and __FILE__
will be equals most of the time in sources files, if not always. And i would strongly discourage you to do this in header files.
It's easier to just put your tests in separate files, only linking them when needed.
Yup, as others say, you're misusing it since you can't compare strings that way in C, and especially not in the preprocessor.
The file that defines int main(int argc, char* argv[]) is the main file. There can be only one such function in an executable.
In addition to what others have said (you can't have the C preprocessor compare strings), be careful with __BASE_FILE__ because it may not correspond to your definition of "main" file. __BASE_FILE__ is the name of the file being compiled, so it's always equal to __FILE__ in source files, and only differs in headers and other included files.
In particular, __BASE_FILE__ is not the name of the file which contains the main() function.
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.