#include <stdio.h>
#define A 1
#if A
printf("Csau");
#endif
int main()
{
return 0;
}
I am trying to run this but my compiler is giving me the error of
main.c:4:9: error: expected declaration specifiers or '...' before
string constant printf("Csau");
Any suggestions why this isn't working ?
P.S. In main function it's working fine with some minor modification.
Edit : Anyway I can show the output outside the main function ?
You can output messages at compile time:
#include <stdio.h>
#define A 1
#if A
#warning "Csau"
#endif
int main()
{
return 0;
}
At runtime you can not print something outside another function body.
Once preprocessed, your code boils down more or less to this:
#include <stdio.h>
printf("Csau");
int main()
{
return 0;
}
And this is not correct C. You cannot call a function outside functions. It doesn't make sense. When you run the program, the system calls your main function and that's it.
You are getting this error because you are trying to call printf from outside of main (or outside of another function)
Edit : Anyway I can show the output outside the main function ?
No. The program starts at the beginning of the "main" function. Putting code outside of functions is syntactically incorrect. Even if the compiler let you do it, the code would never be executed.
The preprocessor doesn't run before main() (aka: before execution) but before compilation. The actual compilation step is fed the results of preprocessing as input, so, in your case, an invalid C program, as you can't have statements outside of functions.
At runtime of your program, there is nothing before entering main(). Of course, your runtime will probably setup a few things, but anything happening before main() is called is not part of your C program.
Related
Following program compiles successfully and print 1000 without even calling a foo() function from our main() function. How is it possible?
#include<stdio.h>
void foo()
{
#define ans 1000
}
int main() {
printf("%d", ans);
return 0;
}
#defineis run by the preprocessor which is staged before the compiler. After the preprocessor is done, the code will look like this:
/* Everything that is inside stdio.h is inserted here */
void foo()
{
}
int main() {
printf("%d", 1000);
return 0;
}
And this is what actually get compiled.
The preprocessor is very important to make header files work. In them, you see this structure:
#ifndef foo
#define foo
/* The content of the header file */
#endif
Without this, the compiler would complain if a header file is included more than once. You may ask why you would want to include a header file more than once. Well, header files can include other header files. Consider this macro, which is useful for debugging. It prints the name of the variable and then the value. Note that you would have to do a separate version for different types.
#define dbg_print_int(x) fprintf(stderr, "%s = %d", #x, x)
This is pretty versatile, so you may want to include it in a header file for own use. Since it requires stdio.h, we include it.
/* debug.h */
#include <stdio.h>
#define dbg_print_int(x) fprintf(stderr, "%s = %d", #x, x)
What happens when you include this file and also include stdio.h in you main program? Well, stdio.h will be included twice. That's why debug.h should look like this:
/* debug.h */
#ifndef DEBUG_H
#define DEBUG_H
#include <stdio.h>
#define dbg_print_int(x) fprintf(stderr, "%s = %d", #x, x)
#endif
The file stdio.h has the same construct. The main thing here is that this is run before the compiler. The define is a simple replacement command. It does not know anything about scope or types. However, as you can see here, there is some basic logic built into it. Another thing that the preprocessor does is to remove all the comments.
You can read more about the C preprocessor here: http://www.tutorialspoint.com/cprogramming/c_preprocessors.htm
The #define is processed by the preprocessor before the compiler does anything. It is a simple text replacement. The preprocessor doesn't even know if the line of code is inside or outside a function, class or whatever [Ref: https://stackoverflow.com/a/36968600/5505997]. Clearly you do not need to call the function to set the value and obviously you will not get any error during compile.
As others have stated, #define is a preprocessor directive, not C source code. See Wiki here.
Point being, in your code #define ans 1000 is not a variable definition, meaning that even if you were calling foo() in the main, you would still not be setting "ans" at runtime, because it is simply not a variable. It is just telling the preprocessor what to do with the "label" "ans", when it finds it in your source code.
In this example, the main() will essentially be calling an empty foo() function:
int main()
{
foo(); // Calls an empty function
printf("%d", ans); // ans will have been substituted by 1000 by the time you start executing you code
return 0;
}
The definition of "ans" will simpy not exist anymore by the time you start executing you main(). This is what the preprocessor does (in part). It finds all the #defines declared in your entire source code and tries to find places in your code where you have used these defines. If you have not used them, it moves on (don't care), if you have, it substitutes the label by the actual defined value.
Using Qt Creator I made these plain C files just to test my understanding:
main.c
#include <stdio.h>
#include "linked.h"
int main()
{
printf("Hello World!\n");
printf("%d", linked());
return 0;
}
linked.h
#ifndef LINKED_H_
#define LINKED_H_
int linked(void);
#endif // LINKED_H
linked.c
int linked()
{
return 5;
}
The IDE shows a warning on the line of linked.h in-between #define LINKED_H_ and int linked(void); which reads
ISO C requires a translation unit to contain at least one declaration
My best guess about what this means is that any header or other C file, if it is in a project, should get used in the main file at least once somewhere. I've tried searching the warning but if this has been answered elsewhere, I'm not able to understand the answer. It seems to me I've used the linked function and so it shouldn't give me this warning. Can anyone explain what's going on?
The program compiles and runs exactly as expected.
I think the issue is that you don't #include "linked.h" from linked.c. The current linked.c file doesn't have any declarations; it only has one function definition.
To fix this, add this line to linked.c:
#include "linked.h"
I don't know why it says this is an issue with linked.h, but it seems to be quite a coincidence that the line number you pointed out just happens to be the line number of the end of linked.c.
Of course, that may be all this is; a coincidence. So, if that doesn't work, try putting some sort of external declaration in this file. The easiest way to do that is to include a standard header, such as stdio.h. I would still advise you to #include "linked.h" from inside linked.c, though.
add a header
#ifndef LINKED_H_
#define LINKED_H_
#include <stdio.h>
int linked(void);
#endif // LINKED_H
The way you wrote the code, you need to use:
extern int linked(void);
(notice the additional "extern"). That might help with the issue.
Also, the code in linked.c should be:
int linked(void)
{
return 5;
}
(Notice the "parameter" - "void").
According to IBM, you need some declaration in the header file, but you do have one. Perhaps LINKED_H_ is defined elsewhere, or the compiler is seeing that it's possible that the precompiler condition might result in an empty parse.
Perhaps this header file will work for you:
linked.h
#ifndef LINKED_H_
#define LINKED_H_
int linked(void);
#endif // LINKED_H
char __allowLinkedHToBeIsoCCompliant = 1;
I'm wondering whether a C file can be both included in another script (through a header file), and also run independently (by having its own main function). That is, the C file can be included to provide its functions to another C script, but can also itself be directly ran to provide some alternate functionality.
For example, a python script can do this;
def functionsToBeImported():
# code to be run by an importing script
pass
if __name__ == '__main__':
# code to be run by this script independently
pass
This code can be imported (import ABOVESCRIPT) by another python file to give access to functionsToBeImported, or independently run (python ABOVESCRIPT.py) to execute the code within the if block.
I've attempted to do this in C via myScript.c:
#include "myScript.h"
void functionsToBeImported() {
}
int main (int narg, char* varg[]) {
}
myScript.h:
#ifndef MY_SCRIPT_H_
#define MY_SCRIPT_H_
void functionsToBeImported();
#endif // MY_SCRIPT_H_
but trying to include this in anotherScript.c:
#include "myScript.h"
int main (int narg, char* varg[]) {
functionsToBeImported();
}
and trying to compile via
gcc -std=c99 -c myScript.c
gcc -std=c99 -c anotherScript.c
gcc -std=c99 -o anotherScript anotherScript.o myScript.o -lm
gives be a compilation error
duplicate symbol _main in:
myScript.o
anotherScript.o
How can I achieve this 'double-use' script?
You cannot link both anotherScript.o and myScript.o, but you could do something like this:
#define main ignored_main
// Include myScript.c, not myScript.h
#include "myScript.c"
#undef main
int main (int narg, char* varg[]) {
functionsToBeImported();
}
I have actually seen things like this in code very widely used in production, although I cannot recommend this style (but it is sometimes a tempting shortcut).
Another option is to include the main function only if a preprocessor macro is defined, like this (in myScript.c):
#include "myScript.h"
void functionsToBeImported() {
}
#ifdef USE_MAIN
int main (int narg, char* varg[]) {
}
#endif // USE_MAIN
This is similar in spirit to the Python approach. But again, you will have to compile this file twice into separate object files.
Note: C files are not scripts.
You cannot have two main functions, as C is a procedural language, meaning you must do one thing at a time (unless you are multithreading, in which case you would still only have one main function).
HOWEVER, there is something quite close to replicating what you want. What you can do is first, write the main method only in the first included file. In the main file, set the atexit() function from the C stdlib.h file (which calls another function at the end of main) to a main2() function (make sure that there is a prototype of each main#() function in the first header as well, and implement all of the functions eventually). Define a macro called MAIN_ONE in the function with the original main. In each consecutively included file, implement the next main and create a macro so that checks to see if the function was implemented can be made. However, the natural, and most efficient way to make a program in C is to just have one main function.
Example:
//In first included file
#include //Some IDEs automaticaly include this. This must be included since it is where the atexit() function resides
#define MAIN_ONE
void main2(); //For the moment, this is only a prototype.
void main3();
//etc. Until you have created the maximum number of main functions that you can have
int main() {
//do something
atexit(main2); // This will execute the function main1() once main returns
//All "fake" mains must be void, because atexit() can only receive void functions
}
//In second included file
#if defined(MAIN_THREE) //start from the maximum number of main functions possible
#define MAIN_THREE //The define is for preprocessor-checking purposes
void main4() {
atexit(main5);
}
#elif defined(MAIN_TWO) //start from the maximum number of main functions possible
#define MAIN_TWO
void main3() {
atexit(main5);
}
//Keep repeating until you reach #ifdef(MAIN_ONE)
#endif
//At the bottom of the main C file
//This is done in order to make sure that all functions have actually been created and reside in memory so that an error does not occur
//(all unused functions are initialized with an empty function here)
#if defined(MAIN_THREE) //start from the maximum number of main functions possible
//Do nothing because if MAIN_THREE is defined when main4(), the last main in my example has already been implemented.
//Therefore, no more functions need to be created
#elif defined(MAIN_TWO) //start from the maximum number of main functions possible
#define MAIN_TWO //Since more mains after main2 can be present, another macro for future checks needs to be defined
void main3() {
}
//Keep repeating until you reach #ifdef(MAIN_ONE)
#endif
#include <stdio.h>
#define main() main(){printf("hi");}int i()
main()
{//empty main
}
what is the use of int i()
That's a pretty silly program, but the purpose of the int i() is so that it will compile - the braces at the end:
{//empty main
}
will cause an error if there isn't a function declaration included in the #define statement. If I delete it, gcc gives the error:
testfile.c:4: error: expected identifier or ‘(’ before ‘{’ token
You can use the -E flag to gcc to see why the int i() is necessary - it will show you the output of the preprocessor without compiling.
Think about what you get if you expand the macro main() in the program:
#include <stdio.h>
main(){printf("hi");}int i()
{//empty main
}
The int i() is needed there to make the remaining { ... } part of a syntactically valid function definition.
As for intention, I can only guess that the point of the macro is to replace the existing main with a stub one. It's a bit icky IMO.
In that code main() will be expanded and the result will end with
int i()
{//empty main
}
what is the use of int i()
It makes the output of a very strange and broken macro compilable
/*you cannot change anything from here below*/
main()
{
exit(0);
}
/*you cannot change anything from here up*/
This was asked during an interview.
I was told to print something on console.
anybody?
Really surprised that nobody posted this yet:
#include <stdio.h>
#if 0
/*you cannot change anything from here below*/
main()
{
exit(0);
}
/*you cannot change anything from here up*/
#endif
int main()
{
printf("Hello, World!");
return 0;
}
Prints at runtime and no undefined behavior whatsoever.
weird question...
int main(void)
{
printf("hello");
return 0;
}
#define main int lol
/*you cannot change anything from here below*/
main()
{
exit(0);
}
/*you cannot change anything from here up*/
#include <stdio.h>
#define exit(c) return puts("foobar"),0
over main
One implementation defined way would be to use the pragma directives to print during compilation.
#pragma message "Compiling " __FILE__ "..."
Or, you could do this with some macros and a printf (but not without introducing UB in some aspect or the other) at runtime.
#define exit(x) printf("Hello, world!")
int main() {
exit(0);
return 0; /* if pre-C99 */
}
#include <stdio.h>
#pragma message("Some foobar")
#error This is an error message
int main()
{
exit(0);
}
I think the interviewer wanted to know if you're aware of the #error directive ... just my 2 cents.
Most answers involve the #define c-preprocessor instruction to change what the program means. Most compilers also support something like
#pragma startup foo()
details depend on the compiler vendor. You can make code run BEFORE main(*) is called that way.
#define exit(x) (printf("Bye"))
int main(int argc,char* argv)
{
exit(0);
getchar();
return 0;
}
Solution 1.
This works without any preprocessor directives in cl and gcc, although I've not tested to make sure I'm not using any extensions:
#include <stdio.h>
static void exit() {
printf("Hello world");
}
/*you cannot change anything from here below*/
main()
{
exit(0);
}
/*you cannot change anything from here up*/
I think it's valid but I can't remember if masking a standard library function is allowed or not.
Solution 2
As several other answers have specified, you can use preprocessor directives, eg:
#define main or exit to be something that calls ifdef
use #if 0 to prevent the existing code being compiled
using #pragma message or #error to print a message at compile time
using #pragma startup to use a different function as main or to run start-up code before main.
Solution 3
If your compiler supports any C++ features in addition to C, there are many answers:
Declare a class with a constructor and a static variable of that type
Put the existing "main" function into a separate namespace (or class definition) and write a different global main
Solution 4
I also looked for any way of forcing a run-time error (stack overflow, out of memory, null dereference, tc), which would normally cause the program to print something, but couldn't find any way that didn't involve running extra code, in which case the extra code might as well be printf.
If you interpreted the question to mean you could not or were not allowed to edit the file by commenting out /* */ or using #ifdef _COMMENT_ME_OUT__ #endif respectively above and below the section you are not allowed to edit and then introducing a new main, then you should give an answer of using another .c file.
If you cannot find a workaround to edit that file, then use a different c file.