How to write C program without using Main...!
When I'm learning how to write ASM file by for a simple C file [of length 3 lines], I got this doubt.
I assembly file I used preamble and post ambles, at function.
There is a great article and creating the smalest possible elf binary here. It has a lot of info of what is required to have something runnable by the os.
This is logical trick. Those who are unaware of it, can learn this trick.
#include<stdio.h>
#include<conio.h>
#define decode(s,t,u,m,p,e,d) m##s##u##t
#define begin decode(a,n,i,m,a,t,e)
void begin()
{
clrscr();
printf("\nHello !!! Kaushal Patel.");
getch();
}
Explanation :
The
pre-processor directive #define with arguments is used to give an impression
that the program runs without main(). But in reality it runs with a
hidden main().
The ‘##‘
operator is called the token pasting or token merging operator. That is
how, I can merge two or more characters with it.
#define decode(s,t,u,m,p,e,d) m##s##u##t
The macro
decode(s,t,u,m,p,e,d) is being expanded as “msut” (The ## operator
merges m,s,u & t into msut). The logic is when I pass
(s,t,u,m,p,e,d) as argument it merges the 4th,1st,3rd & the 2nd
characters.
#define begin decode(a,n,i,m,a,t,e)
Here the
pre-processor replaces the macro “begin” with the expansion
decode(a,n,i,m,a,t,e). According to the macro definition in the previous
line the argument must be expanded so that the 4th, 1st, 3rd & the
2nd characters must be merged. In the argument (a,n,i,m,a,t,e)
4th,1st,3rd & the 2nd characters are ‘m’,’a’,’i’ & ‘n’.
So the third line “void begin” is replaced by “void main” by the pre-processor before the program is passed on for the compiler.
Source :
http://ctechnotips.blogspot.in/2012/04/writing-c-c-program-without-main.html
Here is your answer:->
#include <stdio.h>
extern void _exit(register int);
int _start(){
printf(“Hello World\n”);
_exit(0);
}
Related
#include <stdio.h>
#define MYNUMBER 123
int main()
{
printf("%d", MYNUMBER456);
}
Above code doesn't work because MYNUMBER and MYNUMBER456 are different token.
#include <stdio.h>
#define SECOND(a, b) printf(#a #b);
#define FIRST SECOND
int main()
{
FIRST(hello, world!)
}
But this one works well. My thought is FIRST and FIRST(hello, world!) are different so it should not work. What am I missing?
You can see the macro expansion by using the -E option (cc -E main.c), though you will see a lot of other stuff inserted because of your #include <stdio.h>, and without it you will probable see some default stuff inserted, in your example the main function becomes
int main()
{
printf("hello" "world!");
}
This is because you have defined FIRST to be the same as SECOND which takes two arguments and makes them strings and since there is no comma between them they get concatenated into a single string, macros are just string substitution, in C the preprocessing is traditionally handled by a seperate executable to the compiler and is not as sophisticated as a compiler, so the type matching you would expect in most languages doesn't apply to the preprocessor.
you are correct MYNUMBER and MYNUMBER456 are different and the pre-compiler wont know how to work with MYNUMBER456
however, when you defined FIRST as SECOND , the precompiler would expand FIRST by SECOND and then you actually have SECOND with 2 parameters so it it working
I have a number of definitions consisting of two comma-separated expressions, like this:
#define PIN_ALARM GPIOC,14
I want to pass the second expression of those definitions (14 in the case above) to unary macros like the following:
#define _PIN_MODE_OUTPUT(n) (1U << ((n) * 2U))
How can I extract the second number? I want a macro, call it "PICK_RIGHT", which will do this for me:
#define PICK_RIGHT(???) ???
So that I can make a new macro that can take my "PIN" definitions:
#define PIN_MODE_OUTPUT(???) _PIN_MODE_OUTPUT(PICK_RIGHT(???))
And I can simply do:
#define RESULT PIN_MODE_OUTPUT(PIN_ALARM)
Do not use macros for this. If you must, the following will work by throwing away the left part first so just the number remains. Use with care. No guarantees.
#define PIN_ALARM GPIOC,14
#define RIGHTPART_ONLY(a,b) b
#define PIN_MODE_OUTPUT(a) RIGHTPART_ONLY(a)
#define RESULT PIN_MODE_OUTPUT(PIN_ALARM)
int main (void)
{
printf ("we'll pick ... %d\n", PIN_MODE_OUTPUT(PIN_ALARM));
printf ("or maybe %d\n", RESULT);
return 0;
}
If you want the left part as a string, you can use this (with the same warnings as above), where the left part gets converted to a string by #:
#define LEFTPART_ONLY(a,b) #a
#define PIN_MODE_NAME(a) LEFTPART_ONLY(a)
There is a practical reason this is not entirely without problems. GPIOC is a symbol and as such it is possibly defined elsewhere. Fortunately, it is not a problem if it is undefined, or it is but to a simple type - after all, first thing the macros do is "throw away the left part". But as Jonathan Leffler comments
Note that if GPIOC maps to a macro containing commas, you're likely to get compilation errors.
I'm working in a C program and I came across a problem. I have this
#define NUMBER_OF_OPTIONS 5
#define NAME_OPTION1 "Partida Rapida"
#define NAME_OPTION2 "Elige Nivel"
#define NAME_OPTION3 "Ranking"
#define NAME_OPTION4 "Creditos"
#define NAME_OPTION5 "Exit"
for (iterator = 1; iterator <= NUMBER_OF_OPTIONS; iterator++){
menu_options[iterator-1]= NAME_OPTION + iterator
}
I want that "NAME_OPTION + iterator" takes the value of the corresponding #define. For example if the variable "iterator" is equal to one, I want menu_options[iterator-1] to take the value of NAME_OPTION1, which is "Partida Rapida".
How can I get this?
Essentially, you can't. #define macros are handled by the C Preprocessor and do textual substitution wherever that macro appears in the code. The macro NAME_OPTION has not been defined, so the compiler should complain. C does not allow appending numbers onto strings, or especially onto symbols like NAME_OPTION. Use an array of const char*, which you can then refer to with your iterator.
You can't use defines as this, you can do:
const char *menu_options[5] = {
"Partida Rapida",
"Elige Nivel",
"Ranking",
"Creditos",
"Exit"
};
If you use #define macro, you just tell preprocessor to replace every occurence of defined word by something else before the code is compiled into machine code.
In this case NUMBER_OF_OPTIONS will be replaced by 5, but there's no occurence of NAME_OPTION*, so nothing will be replaced and you'll probably get an error while preprocessing.
Piere's solutions shows how to do it, but I highly doubt that there's an iterator over char *array, so you have to iterate over given array using an integer index.
When using C preprocessor one can stringify macro argument like this:
#define TO_STRING(x) "a string with " #x
and so when used, the result is as follows:
TO_STRING(test) will expand to: "a string with test"
Is there any way to do the opposite? Get a string literal as an input argument and produce a C identifier? For example:
TO_IDENTIFIER("some_identifier") would expand to: some_identifier
Thank you for your answers.
EDIT: For those wondering what do I need it for:
I wanted to refer to nodes in a scene graph of my 3D engine by string identifiers but at the same time avoid comparing strings in tight loops. So I figured I'll write a simple tool that will run in pre-build step of compilation and search for predefined string - for example ID("something"). Then for every such token it would calculate CRC32 of the string between the parenthesis and generate a header file with #defines containing those numerical identifiers. For example for the string "something" it would be:
#define __CRC32ID_something 0x09DA31FB
Then, generated header file would be included by each cpp file using ID(x) macros. The ID("something") would of course expand to __CRC32ID_something, so in effect what the compiler would see are simple integer identifiers instead of human friendly strings. Of course now I'll simply settle for ID(something) but I thought that using quotes would make more sense - a programmer who doesn't know how the ID macro works can think that something without quotes is a C identifier when in reality such identifier doesn't exist at all.
No, you can't unstringify something.
//unstringify test
enum fruits{apple,pear};
#define IF_WS_COMPARE_SET_ENUM(x) if(ws.compare(L#x)==0)f_ret=x;
fruits enum_from_string(wstring ws)
{
fruits f_ret;
IF_WS_COMPARE_SET_ENUM(apple)
IF_WS_COMPARE_SET_ENUM(pear)
return f_ret;
}
void main()
{
fruits f;
f=enum_from_string(L"apple");
f=enum_from_string(L"pear");
}
You can create an identifier from a string, this operation is called token-pasting in C :
#define paste(n) x##n
int main(){
int paste(n) = 5;
printf("%d" , x5);
}
output : 5
The scope of #define is till the end of the file. But where does it start from.
Basically I tried the following code.
#include<stdio.h>
#include<stdlib.h>
#define pi 3.14
void fun();
int main()
{
printf("%f \n",pi);
#define pi 3.141516
fun();
return 0;
}
void fun(){
printf("%f \n",pi);}
The output of the above program comes out to be
3.140000
3.141416
Considering preprocessing for main the value of pi should be 3.141516
and outside main 3.14. This is incorrect but please explain why.
The C preprocessor runs through the file top-to-bottom and treats #define statements like a glorified copy-and-paste operation. Once it encounters the line #define pi 3.14, it starts replacing every instance of the word pi with 3.14. The pre-processor does not process (or even notice) C-language scoping mechanisms like parenthesis and curly braces. Once it sees a #define, that definition is in effect until either the end of the file is reached, the macro is un-defined with #undef, or (as in this case) the macro is re-defined with another #define statement.
If you are wanting constants that obey the C scoping rules, I suggest using something more on the lines of const float pi = 3.14;.
The scope of a #define is from the occurrence, to the end of the file (or a corresponding #undef), regardless of any intervening C scopes.
When you have preprocessor question:
gcc -E foo.c > foo.i; vim foo.i
Preprocessor has no concept of "scope" -- it manipulates the text of the program, without any idea of what the text is
Symbol is defined from its definition until the end of the compilation unit (a source file and and files it includes)
Here is what roughly looks like after the preprocessor done with your file:
void fun();
int main()
{
printf("%f \n",3.14);
fun();
return 0;
}
void fun(){
printf("%f \n",3.141516);}
These are the lines that go to the compiler for compilation(I discarded many of the codes for the sake of clarity, only kept what you coded). As the preprocessor replaces the #define directive with the text/value you provided thus you don't see the #define directives anymore after preprocessing. So it is clear what is going to be printed on the console/terminal.
As far as I know, the preprocessor uses #define statements in the order that it encounters them. In that case, your first printf statement correctly prints 3.14 and the second 3.141516 (is there a typo in the output from your program?).