Zombo
Zombo

Reputation: 1

One line C program with include?

Right now I have this

#include <zlib.h>
int main ()
{
    puts (ZLIB_VERSION);
}

As an exercise, is there any way I could get it to compile on one line, something like

#include <zlib.h>; int main (){ puts (ZLIB_VERSION); }

I can get it to compile on two lines, but the include is preventing one line.

Upvotes: 3

Views: 6047

Answers (4)

roim
roim

Reputation: 4930

Being a bit naive, standard C requires an empty newline at the end of your source code, so 1-line programs that actually do something are impossible.

Update: this is no longer required in C++11

Upvotes: -1

paxdiablo
paxdiablo

Reputation: 881113

No, the include directive goes on its own line.

The relevant portion of the standard is C11 6.10.2 Source file inclusion where it defines the #include directive as one of:

# include <h-char-sequence> new-line
# include "q-char-sequence" new-line

Note that the newline is an integral part of the directive.

I'm not entirely certain why you need it on one line anyway. Most programs which can output text can quite easily inject newlines into the stream anyway, such as with:

pax> printf '#include<stdio.h>\nint main(void){return puts("Hi"),0;}' \
...> | gcc -o testprog -xc -

pax> ./testprog
Hi

Upvotes: 1

MSN
MSN

Reputation: 54554

It depends on how many files you are limited to. If it isn't one, then you can add another file that contains all the code and #include that one. E.g.:

some_header.h:

include <zlib.h> 
int main () 
{
    puts (ZLIB_VERSION); 
}

main.c:

include "some_header.h"

But I don't think that's what you really want. Like everyone else said, the preprocessor deals with lines and there is no delimiter in C to start a new line for the preprocessor. (There is the \ delimiter that makes the preprocessor treat the next line as a continuation of the current one, but not the inverse.)

Upvotes: 0

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

There's no way to do exactly what you want. With that said, if this is part of a build system, it would be a lot better to use the -E option to the compiler to preprocess a file containing simply

#include <zlib.h>
ZLIB_VERSION

and then parse the output. This way you avoid running a program generated by the compiler, so your build doesn't break when cross-compiling.

Upvotes: 5

Related Questions