Is it possible to write a C program without using header files? - c

Is it possible to write a C program without using header files? If it is, how?

Of course:
int main() {
return 0;
}
Or even:
int printf(const char *format, ... ); // could be copied from stdio.h
int main() {
printf("Hello, world!\n");
return 0;
}
The #include directive effectively just includes the header file's content in the source file.

Of course.
A header file is just a file that gets included in some source files, and when you include a file you just copy its content.
You can write any program you want to without any #include, but you'd have to manually put the stuff you need in your source files.

Yes it is possible to write a simple program without header files, but why would you do that ?
Header files are useful to share definitions, constants, functions prototypes, etc between multiple files or modules.

Sure. Because header files written in C. But it's hard.
printf example:
int printf(const char *format, ...);
scanf example:
int scanf(const char *format, ...);
and more...

Absolutely yes, you can even inlinme the function prototype you possibly need in the c file itself

I was trying to write the shortest code possible in c, so i tried removing the header files from source code.To my surprise even a program with printf compiled with just a warning and ran successfully.How does that happen??
main()
{
printf("Hello World\n");
}

It's possible, but by all means, avoid from not using it if not necessary.

Yes you can wirte a program without #include , but it will increase the complexity of the programmer means user have to write down all the functions manually he want to use.It takes a lot of time and careful attention while write long programs.Yes ,simple program like given above have no problem to write without including any library function call.

#include<"filename">
will help you to implement and use the functions present in the file,
i.e.
#include< stdio.h>
will help us to use the built functions present in the stdio.h file - printf and scanf
When you dont use #include< stdio.h> in your program , it still will not cause any problems, its only when you may use printf or scanf it may cause the program to generate a warning at the time of compilation (for implicit declaration of function printf.)
More Details on the same , Below link is the screenshot for the same for the printf used without specifying #include<stdio.h>
image

Related

Why is it sometimes valid to write an include statement in a codeblock?

I amcoming from a python background, where the following is valid:
def f():
import someLibrary
someLibrary.libraryFunction()
So when I needed to debug C code, I wrote, in the middle of my function:
void f(int param)
{
int status;
/* other code */
#include <stdio.h>
printf("status: %d", status);
/* more code */
}
And it compiled and worked as I expected. Later it was pointed out to me that this shouldn't compile, since the C pre-processor literally replaces the #include~ statement with the contents ofstdio.h`.
So why was this valid code?
it was pointed out to me that this shouldn't compile, since the C pre-processor literally replaces the #include statement with the contents ofstdio.h.
The logic on that doesn't make sense. Just because the pre-processor inserts the text from the stdio.h file doesn't mean it should not compile. If there's nothing in that file that would result in a compile error, then it will compile just fine.
Furthermore, headers usually have a multiple inclusion guard in them. So if they were included already previously, any further attempts to include it have no effect. In this case, if <stdio.h> was already included previously in the file (directly or indirectly), the #include will have no effect.
With that being said, don't do that though. In C, standard headers are not supposed to be included while inside a function scope.
Yeah, C and Python are pretty different in this respect.
It is correct that the preprocessor replaces the #include directive with the contents of the included file prior to compilation.
Whether it leads to a compilation error or not depends entirely on the contents of the included file. Standard headers like stdio.h don't contain any executable statements - they only contain things like typdefs, function declarations, other macros, etc. They also usually have some kind of #include guards in place that prevent them from being loaded more than once per translation unit (that is, if you #include a file that includes stdio.h, and then #include <stdio.h> directly in the same source file, the contents of stdio.h will only be loaded once).
Theoretically, there's no problem with including stdio.h at random points in the code, but it can lead to problems. In this case all of stdio.h's contents will only be visible to the body of f - not a problem if only f needs to use anything in stdio.h, but otherwise it will lead to headaches.
Standard headers are best included at the beginning of the source file.

How to write a quine program without main()

I went through all sorts of quine problems, but my task was to get a quine problem without main(), and loops are also forbidden.
Without loop, it is easy, but I can't figure out how to write one without main(). Can anyone help me or provide me with a link?
You cannot create a (non-freestanding) C program without a main() function. Thus, creating a quine in C without a main() is impossible in the usual sense.
That said, depending on how you define a quine, you might be able to construct a source file which fails to compile, but for which the compile error (on a certain specific compiler) is the contents of the source file.
First thing its impossible to write program without main function because compiler always starts execution from main() function, without main function linker will not be aware of start of data segment.
Yeah but playing with some tricks with preprocessor you can do it, but this is not a good method to do that.
http://www.gohacking.com/2008/03/c-program-without-main-function.html
This might help you.
Take a look here too:
Is a main() required for a C program?
#include <stdio.h>
int
foo(void) {
printf("pong!\n");
return 0;
}
int main() __attribute__((weak, alias("foo")));
There is main() declaration, but not definition.

Including header files more than once

#include <stdio.h>
#include <stdio.h>
int main ()
{
printf ("hello world");
return 0;
}
when I compile this, the compiler doesn't give any warning/error for including stdio.h twice. Why is it so? Aren't the functions scanf, printf etc. declared and defined twice now?
Thanks, in advance
Typically, header files are written similar to the below example to prevent this problem:
#ifndef MYHEADER
#define MYHEADER
...
#endif
Then, if included more than once, then 2nd instance skips the content.
In addition to the use of include guards, as pointed out by Mark Tolonen's answer, there is no problem with declaring a function more than once, as long as the declarations are compatible. This is perfectly fine:
int foo(int, char *);
int foo(int a, char *p);
extern int foo(int x, char y[]);
In fact, since every definition is also a declaration, whenever you "forward-declare" a function declared in the same file, you are declaring the function twice.
What is not OK is to create multiple external definitions of a function; but well-written header files should not create external definitions - only declarations. The (single) definition of the printf and scanf functions should be in an object file, which is linked with your program when it is built.
No, the header files usually define a flag and then use #ifndef to include themselves only if the flag was undefined.
Open one up and see.
As an aside, doing the "#ifndef" trick is appropriate for headers used by other people (like the standard headers).
If you need the #ifndef for a "private" program, then you are doing it "wrong". That is, you can and should organize headers within a project so they are not included more than once.
One reason that this is helpful is that keeps headers you think you have deleted from popping up again.
Since you can't control how public headers are used, this trick is reasonable for public headers. This trick is completely unnecessary for private headers.

possible flaws in 'including *.c files' style C programming

I came across some codes in the following way
//file.c
#include <stdlib.h>
void print(void){
printf("Hello world\n");
}
and
//file main.c
#include <stdio.h>
#include "file.c"
int main(int argc, char *argv[]){
print();
return EXIT_SUCCESS;
}
Is there any flaw in this kind of programming style? I am not able to make out the flaw although I feel so, because somewhere I read that separating the implementation into *.h and *.c file helps compiler check for consistency. I don't understand what is meant by consistency.
I would be deeply thankful for some suggestions.
--thanks
Nothing prevents you from including .c files. However, separating declaration (in .h files) and implementation (and .c files) and then including only .h files has several advantages :
Compile time. Your declaration usually changes less than your implementation. If you include only .h files, and makes a change in your implementation (in the .c file), then you only have to recompile one .c file, instead of all the files which include the modified file.
Readability and management of interfaces. All your declarations can be checked in a single glance at the (usually) small .h file whereas the .c file is filled with lines and lines of code. Moreover it helps you determine which file see which functions and variables. For example, to avoid having a global variable included where you don't want it.
It's a common expectation that the compiler should compile .c files. .h files are not directly given to the compiler. They are usually only included within .c files.
Thus, your code is expected to compile by something like:
gcc main.c file.c
rather than only gcc main.c. That command would fail in the linking stage as it sees duplicate symbols.
You're going to have problems if you include file.c in more than one source code file which combine to make a library/executable, since you'll have duplicate method implementations. The above strikes me as a poor means of sharing/reusing code, and is not to be recommended.
It is not uncommon to include data in another file if it is more convenient to separate it from the code. For example, XPM or raw BMP data in a char array could be included to embed an image in the program in this way. If the data is generated from another build step then it makes sense to include the file.
I would suggest using a different file extension to avoid confusion (e.g. *.inc, *.dat, etc.).
Yes, this is permitted.
Using this is an advanced topic.
It slows down development compile time (cheaper to compile only what is necessary).
It speeds up deployment compile time (all files are out of date).
It allows the compiler to inline functions across module boundaries.
It allows a trick to control exported symbols from a library while keeping it modular.
It might confuse the debugger.
There is nothing wrong from a C language perspective with including a .c file in a program. The C language cares not about the extension of the file, C++ in fact often omits an extension on certain header files to avoid conflicts.
But from the perspective of a programmer, yeah this is odd. Most programmers will operate on the assumption that a .c file will not be included and this can cause problems via incorrect assumptions. It's best to avoid this practice. If you find you must use it, it's a sign of poor design.
In the .h files you should place function prototypes. For example, in your code you should have:
//file.h
void print(void);
//file.c
void
print(void)
{
printf("Hello world\n");
}
//file main.c
#include <stdio.h>
#include "file.h"
int main(int argc, char *argv[]){
print();
return EXIT_SUCCESS;
}
There are only two reasons that I know of for including C files (and which make sense):
inline functions which are non trivial, but that's really a matter of style
share implementation of private (static) functions by including the same file in several other files. That's actually the only way to do it in a purely platform independent way (but toolchain specific tricks like hidden attribute for gcc, etc... are much better if they are available)
The flaws:
you compile several times the same code
if not used sparingly, it quickly leads to multiple defined symbols for public symbols, in a way which is difficult to debug (include files which include other files...)
It is bad style, but one other reason to do it is that it can be used a part of a trick using the ## token concatenation operator to do a kind of poor man's templating in C.
Note that this fairly evil, isn't recommended, and will produce code that's hard to debug and maintain, but you can do something like the following:
mytemplate.c:
MyTemplateFunction_ ## MYTYPE(MYTYPE x)
{
// function code that works with all used TYPEs
}
main.c:
#define MYTYPE float
#include "mytemplate.c"
#undef MYTYPE
#define MYTYPE int
#include "mytemplate.c"
#undef MYTYPE
int main(int, char*)
{
float f;
int i;
MyTemplateFunction_float(f);
MyTemplateFunction_int(i);
return 0;
}
The evils of macros can be exacerbated:
file1.c
#define bottom arse
file2.c
int f()
{
int arse = 4;
bottom = 3;
printf("%d", arse);
}
main.c
#include "file1.c"
#include "file2.c"
void main()
{
f();
}
Indeed a convoluted example. But usually you wouldn't notice it because a macro's scope is the file it is in.
I did actually get this bug, I was importing some lib code into a new project and couldn't be bothered to write the Makefile, so I just generated an all.cpp which included all the sources from the library. And it didn't work as expected due to macro pollution. Took me a while to figure it out.
It's fine for the programs of this length.

How does splint know my function isn't used in another file?

Splint gives me the following warning:
encrypt.c:4:8: Function exported but not used outside encrypt: flip
A declaration is exported, but not used outside this module. Declaration can
use static qualifier. (Use -exportlocal to inhibit warning)
encrypt.c:10:1: Definition of flip
Since I called splint only on this file how does it know that?
#include <stdio.h>
#include <stdlib.h>
int flip( int a)
{
int b;
b = a;
b ^= 0x000C;
return b;
}
int blah(int argc, char *argv[]) {
FILE *fp = NULL, *fpOut=NULL;
int ch;
ch = 20; flip(20); return (ERROR_SUCCESS);
}
I even got rid of main so that it could not figure out that the file is complete in any way. I am totally stumped!
You might find that if you included a header that declared flip() - as you should, of course - then splint would not complain. You should also declare blah() in the header as well.
I'm not wholly convinced that this is the explanation because blah() is not used at all (though it uses flip()) and you don't mention splint complaining about that.
However, it is a good practice to make every function (in C) static until you can demonstrate that it is needed outside its source file, and then you ensure that there is a header that declares the function, and that header is used in the file that defines the function and in every file that uses the function.
In C++, the 'every function should be static' advice becomes 'every function should be defined in the anonymous namespace'.
Since I called splint only on this file how does it know that?
You have answered your question. You've fed in one file to lint, so lint knows there is only file to be taken care of (apart from the standard header includes, of course).
int flip() is not declared as static, so it can be potentially used externally. Since you invoked splint with only one source file, it correctly says that your function, if not used externally, must be declared static
It can only report on what it sees. Ignore the warning or follow the instructions to inhibit it if you know better than what it says. Don't assume that a tool like this necessarily knows your program better than you do.
If it really is not intended to be used outside of the file, you can declare it static and it should correct the problem, but it will be inaccessible from other files.

Resources