For a very specific project, I need to write a 16-bit program in C and I'm using Microsoft QuickC in MS-DOS to write this program. Now I'm pretty sure the syntax of my program is correct but the program just won't compile and it thinks I have syntax errors. Is this because C-compilers in MS-DOS using an older version of C with different syntax?
#include<stdio.h>
main()
{
printf("Hello World!");
}
Not even that simple hello world program will compile and run.
you should define main as int
so change your code to :
int main() { // define main as an int returning function
// your code
return 0; // Also make sure you have return statement in main
}
and it will compile
Here is what it says in the standards:
1 The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int :
int main(void) { /* ... */ }
Edit:
Ok from your comments .. you are now getting this error:
C1024: cannot open include file 'stdio.h'
Here is a cause and solution from microsoft:
http://support.microsoft.com/kb/97809
You can't omit the type of the function main, or any other C function, for that matter. So, you want
void main() { ... }
or
int main(int argc, char **argv) { ... }
although with the latter one the compiler will usually require you to return a value.
Related
In C90, can I redefine main and give it another name, and possibly add extra parameters using #define?
Have this in a header file for example:
#include <stdio.h>
#include <stdlib.h>
#define main( void ) new_main( void )
int new_main( void );
The header doesn't show any errors when compiling.
When I try compiling it with the main C file, however, I keep getting an error
In function '_start': Undefined reference to 'main'
No, you cannot do that, because it would be against language and OS standards. The name main and its arguments argc, argv and environ constitute a part of system loader calling conventions.
A bit simplifying explanation (no ABI level, just API level) ensues. When your program has been loaded into memory and is about to start, the loader needs to know which function to call as an entrypoint, and how to pass its environment to it. If it was be possible to change the name of main and/or its parameter list, it would have been needed to communicate details of new calling interface back to the loader. And there is no convenient way to do it (apart from writing your own executable loader).
In function '_start': Undefined reference to 'main'
Here you can see an implementation detail of Linux/POISX ELF loader interface. The compiler adds function _start to your program behind the scenes, which is an actual program entrypoint. _start is tasked to do extra initialization steps common to most programs that use LibC. It is _start that later calls your main. Theoretically, you could write a program that has its own function called _start and no main and it would be fine. It is not trivial as you will have to make sure that the default _start code is no longer being attached to your program (no double definitions), but it is doable. And no, you cannot choose other name than _start for the same reasons.
The presence of #define main new_main within a compilation unit will not affect the name of the function the implementation will call on program startup. The implementation is going to call a function called main regardless of any macros you define.
If you are going to use a #define like that to prevent the primary declaration of main() from producing a function by that name, you'll need to include a definition of main() somewhere else; that alternate version could then invoke the original. For example, if the original definition didn't use its arguments, and if the program exits only by returning from main() [as opposed to using exit()] you might put #define main new_main within a header file used by the primary definition of main, and then in another file do something like:
#include <stdio.h>
#include <conio.h> // For getch() function.
int main(void)
{
int result = main();
printf("\nExit code was %d. Strike any key.\n", result);
getch();
return result;
}
In most cases, it would be better to add any such code within the ordinary "main" function, but this approach can be useful in cases where the file containing main is produced by code generation tools on every build, or for some other reason cannot be modified to include such code.
No you cannot (as Grigory said).
You can however, immediate call your proxy main,
int
your_new_main(int argc, char* argv[], char* envp[]) {
... //your stuff goes here
}
//just place this in an include file, and only include in main...
int
main( int argc, char* argv[], char* envp[])
{
int result = your_new_main(argc, argv);
return result;
}
As far as whether envp is supported everywhere?
Is char *envp[] as a third argument to main() portable
Assuming you're using gcc passing -nostdlib to your program, and then set a new entry, by passing this to gcc which passing it to the linker, -Wl,-enew_main. Doing this won't give you access to any of the nice features that the C runtime does before calling your main, and you'd have to do it yourself.
You can look at resources about what happens before main is called.
What Happens Before main
I'm trying to port some GCC nested function to clang. As gcc nested function is not supported in clang, i need to use c-block instead.
But i want to have the block definition after the call to it. (I need this order because code is generated from MACRO and i can not arrange this order)
So in gcc i have this pseudo code :
foo(){
auto void bar (void);
...
bar()
...
void bar(void) {
...some stuff
}
}
You i can do this in C-block clang function ?
This code works fine
int main() {
void (^hello)(void);
hello = ^(void){
printf("Hello, block!\n");
};
hello();
return 0;
}
But the following code
int main() {
void (^hello)(void);
hello();
hello = ^(void){
printf("Hello, block!\n");
};
return 0;
}
failed with an segfault.
In your second example, hello has not been defined before you call it, so it is an undefined symbol. You have to tell the compiler what something is before you can use it.
In your pseudocode, a function prototype preceeds everything, which gets around the error by telling the compiler "this will be defined later on."
I am new to C programming and I am currently learning loops. In the below program,
#include<stdio.h>
main()
{
int i;
for(i=1;i++<=5;printf("%d",i));
}
i tried to compile in dev c++ compiler but it is giving error "[Error] ld returned 1 exit status"
You need to include the <stdio.h> header, and also, main needs a return type (int) and a return value. Changing the program to this will make it compile (at least it did using GCC) and run:
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
for(i=1;i++<=5;printf("%d",i));
return 0;
}
The quotes you used in the ā%dā are illegal too, use normal quotes: "%d".
Apart from that, doing the printf inside the loop head might be legal, but it's pretty bad style. Usually in a for-loop you would have have initialization;condition;increment(or decrement or w/e) in the head, and do side-effects in the body of the statement.
I would try writing the for loop as:
for(i=1;i < 6;i++) { printf(ā%dā,i); }
I have run this program manually on my notebook and i got Output 23456
Then i run this on Dev c++ and it is giving the same output 23456 without any error and i have just copied and pasted from ur question dun know why its showing error on ur runtime may be u have not saved it as C file
I wrote little program to print "Hello world" in C. I'm not a C programmer, but I liked to try it. In my program there is an error. Please tell me what is it?
This is my program:
int main(){
printf("Hello World");
}
I wrote this with my Java Experiences. I can't find what is wrong.
You can't directly use printf() function as in Java. You should tell the compiler that you are going to use the input/output stream. You can tell it in this line:
#include <stdio.h>
and also you should enter this line at the end of the source code:
return 0;
this will tell the compiler :
"If the program succeed It will return 0 otherwise It will return any other number"
This means if your program is successful main() function will return 0. Then the compile know the program is Ok.
Then at last your complete code is:
#include <stdio.h>
int main() {
printf("Hello world");
return 0;
}
To compile this and see the word "Hello World", just save this file as a .c file and Open cmd in your program directory and type
gcc hello.c -o hello && hello
(Replace the 'hello.c' with your filename, and 'hello' with the name you want to put with your .exe file)
Remember My computer is Windows. And this compile code is for windows. If your OS is UNIX like OS. then use this code to compile:
gcc hello.c -o hello
./hello
A full hello world program in C:
#include <stdio.h>
int main(void) {
printf("Hello World\n");
return 0;
}
Then compile (assuming gcc) and execute it:
gcc -o test test.c
./test
First, you have to use a header file.
#include <stdio.h>
What that does is bring up a header file with a bunch of commands in them. That will make it recognize the "printf" piece of code.
Next, you have to close your program. By not having a closing statement, the program will not compile because it doesn't know if that is the end of the code. Use this at the end of your program...
return 0;
That closes the program, meaning that the compiler can stop looking for other code. You may also want to look at some programming manuals (there are dozens of free online ones) to learn about the syntax.
One last thing: Most pieces of C code require a semicolon at the end. This is not true for the "int main" statement, nor is it for the header file which I have defined above. The "return" function that closes the program, does however, need a semicolon.
Hoped this helped.
Should also include a pause at the end:
#include <stdio.h>
int main(void) {
printf("Hello World\n");
//Read a character from the console
getchar();
return 0;
}
Just like import in Java programs, in here you have to include libraries you're using in your program. You have used library function printf, but not included stdio.h.
I agree there are many ways to write one of the simplest way is
#include<stdio.h>
int main(void){
printf("Hello World\n");
return 0;
}
You can even use different ways as suggested above.
You should first look at the structure of "main". Try to understand the various parts as already explained so well in the above answers.
"#include" : The preprocessing directives to be included in the program. But why? Because you are trying to use the functions defined inside them.
int : The return type of "main" program. But why? Because the function calling "main" needs to know if the "main" program has functioned correctly.
main : The entry point of your code. Dont ask why here :-)
main( void ) : To tell the compiler that we are not passing any arguments to program "main"
return 0 : Beacuse you promised "main" that you will return something if "main" will function properly.
Finally the code:
#include <stdio.h>
int main( void )
{
printf( "Hello World\n" ) ; //Notice the '\n' here. Good coding practice.
return 0 ;
}
#include <stdio.h> //Pre-processor commands<br/>
void main() //Starting point of the program<br/>{ //Opening Braces
printf("Hello World\n"); //Print Hello World on the screen<br/>
return 0;
} //Ending Braces
Check it once it will work, I have written it with comments:
#include<stdio.h> //Pre-processor commands
void main() {
printf("Hello World\n"); //Print Hello World on the screen
}
A full hello world program in C:
#include <stdio.h>
int main(void) {
printf("Hello World\n");
return 0;
}
Then compile (assuming gcc) and execute it:
gcc -o test test.c
./test
You can't use printf() function as in Java. You have to tell the compiler what you are going to use.
You can tell this as follows:-
#include <stdio.h>
You must enter this line in last:-
return 0;
Then Your complete code is:-
#include <stdio.h>
int main(){
printf("Hello World");
return 0;
}
For compiling this and see the word "Hello World", just save this file as a .c file and Open cmd in your program directory and type:-
gcc hello.c -o hello && hello
(Replace the 'hello.c' with your filename, and 'hello' with the name you want to put with your .exe file)
Remember My computer is Windows. So I can compile only for Windows OS.
#include <stdio.h>
int main() {
// printf, used to print (display) Hello World
printf("Hello World ! ");
// return 0, as the main function is of type int so it must return an integer value
return 0;
}
I am reading Microsoft's CRT source code, and I can come up with the following code, where the function __initstdio1 will be executed before main() routine.
The question is, how to execute some code before entering the main() routine in VC (not VC++ code)?
#include <stdio.h>
#pragma section(".CRT$XIC",long,read)
int __cdecl __initstdio1(void);
#define _CRTALLOC(x) __declspec(allocate(x))
_CRTALLOC(".CRT$XIC") static pinit = __initstdio1;
int z = 1;
int __cdecl __initstdio1(void) {
z = 10;
return 0;
}
int main(void) {
printf("Some code before main!\n");
printf("z = %d\n", z);
printf("End!\n");
return 0;
}
The output will be:
Some code before main!
z = 10
End!
However, I am not able to understand the code.
I have done some google on .CRT$XIC but no luck is found. Can some expert explain above code segment to me, especially the followings:
What does this line _CRTALLOC(".CRT$XIC") static pinit = __initstdio1; mean? What is the significance of the variable pinit?
During compilation the compiler (cl.exe) throws a warning saying as below:
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
stdmacro.c
stdmacro.c(9) : warning C4047: 'initializing' : 'int' differs in levels of indirection from 'int (__
cdecl *)(void)'
Microsoft (R) Incremental Linker Version 9.00.30729.01
Copyright (C) Microsoft Corporation. All rights reserved.
/out:stdmacro.exe
stdmacro.obj
What is the corrective action needs to be done to remove the warning message?
Thanks in advance.
Added:
I have modified the code and give type to pinit as _PIFV. Now the warning message is gone.
The new code is as follows:
#include <stdio.h>
#pragma section(".CRT$XIC1",long,read)
int __cdecl __initstdio1(void);
typedef int (__cdecl *_PIFV)(void);
#define _CRTALLOC(x) __declspec(allocate(x))
_CRTALLOC(".CRT$XIC1") static _PIFV pinit1 = __initstdio1;
int z = 1;
int __cdecl __initstdio1(void) {
z = 100;
return 0;
}
int main(void) {
printf("Some code before main!\n");
printf("z = %d\n", z);
printf("End!\n");
return 0;
}
A simple way to do this.
#include <iostream>
int before_main()
{
std::cout << "before main" << std::endl;
return 0;
}
static int n = before_main();
void main(int argc, char* argv[])
{
std::cout << "in main" << std::endl;
}
This is what _CRTALLOC is defined as:
extern _CRTALLOC(".CRT$XIA") _PVFV __xi_a[];
extern _CRTALLOC(".CRT$XIZ") _PVFV __xi_z[];// C initializers
extern _CRTALLOC(".CRT$XCA") _PVFV __xc_a[];
extern _CRTALLOC(".CRT$XCZ") _PVFV __xc_z[];// C++ initializers
It's a table of things to pre-initialise, of which a pointer to your function __initstdio1 is placed.
This page described CRT initialisation:
http://msdn.microsoft.com/en-us/library/bb918180.aspx
In C++ at least, you don't need all that implementation specific stuff:
#include <iostream>
struct A {
A() { std::cout << "before main" << std::endl; }
};
A a;
int main() {
std::cout << "in main" << std::endl;
}
I wrote an award-winning article about this on CodeGuru a while ago.
There's some information here (search for CRT). The significance of variable pinit is none, it's just a piece of data placed in the executable, where the runtime can find it. However, I would advise you to give it a type, like this:
_CRTALLOC(".CRT$XIC") static void (*pinit)()=...
The linker warning probably just warns you you have a function that has int return type, but doesn't return anything (probably you'd better change the return type to void).
Even in C, there is a need for some code to be run before main() is entered, if only to transform the command line into the C calling convention. In practice, the standard library needs some initialization, and the exact needs can vary from compile to compile.
The true program entry point is set at link time, and is usually in a module named something like crt0 for historical reasons. As you've found, the source to that module is available in the crt sources.
To support initializations that are discovered at link time, a special segment is used. Its structure is a list of function pointers of fixed signature, which will be iterated early in crt0 and each function called. This same array (or one very much like it) of function pointers is used in a C++ link to hold pointers to constructors of global objects.
The array is filled in by the linker by allowing every module linked to include data in it, which are all concatenated together to form the segment in the finished executable.
The only significance to the variable pinit is that it is declared (by the _CRTALLOC() macro) to be located in that segment, and is initialized to the address of a function to be called during the C startup.
Obviously, the details of this are extremely platform-specific. For general programming, you are probably better served by wrapping your initialization and your current main inside a new main():
int main(int argc, char **argv) {
early_init();
init_that_modifies_argv(&argc, &argv);
// other pre-main initializations...
return real_main(argc,argv);
}
For special purposes, modifying the crt0 module itself or doing compiler-specific tricks to get additional early initialization functions called can be the best answer. For example, when building embedded systems that run from ROM without an operating system loader, it is common to need to customize the behavior of the crt0 module in order to have a stack at all on which to push the parameters to main(). In that case, there may be no better solution than to modify crt0 to initialize the memory hardware to suit your needs.