473,322 Members | 1,504 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

program having printf() function invocation without including <stdio.h>

Hi Everyone,

int main()
{
printf("not included stdio.h");
}

Yes, i haven't included stdio.h and my compiler would generate a
warning and would assume that it would return a int, my question is how
does the linker manage to link the function invocation to the proper
printf function?
and does including a header file having function prototype help the
linker in any way?

Jan 13 '07 #1
18 2822
In article <11**********************@11g2000cwr.googlegroups. com>,
<sa*****@yahoo.co.inwrote:
>Hi Everyone,

int main()
{
printf("not included stdio.h");
}

Yes, i haven't included stdio.h and my compiler would generate a
warning and would assume that it would return a int, my question is how
does the linker manage to link the function invocation to the proper
printf function?
and does including a header file having function prototype help the
linker in any way?
The droids will tell you that this is undefined behavior, for all the
usual drecky reasons.

Jan 13 '07 #2
sam_...@yahoo.co.in wrote:
Hi Everyone,

int main()
{
printf("not included stdio.h");
}

Yes, i haven't included stdio.h and my compiler would generate a
warning and would assume that it would return a int, my question is how
does the linker manage to link the function invocation to the proper
printf function?
and does including a header file having function prototype help the
linker in any way?
The prototype is primarily for the compiler's benifit, as it specifies
the number and type of parameters the function expects, if any, and the
type of value it returns, if any. It helps the compiler to output the
correct object code when the function is called and to perform the
correct conversions on the return value.

The linker will simply search the library archive files specified for
the label 'printf'/'_printf' and link in the object code. It doesn't
need the function's prototype.

Strictly according to the standard calling a function whose prototype
is not in scope leads to undefined behaviour. It might work for simpler
functions on some implementations. Some compilers like gcc, often have
the ability to "magically" recognise certain common functions and
include the code inline, but all these are implementation specific
behaviour. You cannot portably rely on them.

Jan 13 '07 #3
sa*****@yahoo.co.in a écrit :
Hi Everyone,

int main()
{
printf("not included stdio.h");
}

Yes, i haven't included stdio.h and my compiler would generate a
warning and would assume that it would return a int, my question is how
does the linker manage to link the function invocation to the proper
printf function?
and does including a header file having function prototype help the
linker in any way?
1) Linkers deal with object files, this has nothing to do with header
files.
2) Header files describe interfaces of functions and modules. This has
nothing to do with object files.

Please keep those apart.

Now, the interfaces descriptions are for the compiler, that generates
code according to those descriptions.

When (in C ) a prototype is not in scope, an automatic
prototype is provided by the compiler. It assumes a function that
has an undertemined number of arguments and returns an int.

In both cases, whether a prototype is in scope or not,
an external reference to a function is issued by the compiler.
In this case the object code would contain an external
reference to the function "printf" (or "_printf", it depends
on the compiler).

The linker goes through the object files and sees:
"Mmmm this is an external reference to the printf function.
Let's look if I find it somewhere".

Then, depending on the linker, it will find it or not in the
libraries it uses BY DEFAULT.

Default libraries vary from compiler system to compiler system.
At least the startup code is ALWAYS automatically included,
then, most compilers assume the C library as a default
library, i;e. one that you do not need to include in the
linker command line. Other compilers may differ, for example some
braindead compiler systems force you to write the math
library as an extra command line option, and it is not
included by default, so if you use the sqrt function for
instance, compilation will fail unless you tell the linker to
add the math library.

Others will include a lot of default libraries so that your
code mostly will link without specifying any extra library
Microsoft Visual C for instance will include all these:

comctl32.lib shlwapi.lib kernel32.lib user32.lib gdi32.lib
winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib
oleaut32.lib uuid.lib odbc32.lib odbccp32.lib

Other compiler systems will be less bloated, for instance
lcc-win32 includes just 6-7 libraries.

Then, the answer to your question is simple:
The linker finds the printf function in the C library of
the compiler that is included by default.

jacob

Jan 13 '07 #4
santosh <sa*********@gmail.comwrote:
Strictly according to the standard calling a function whose prototype
is not in scope leads to undefined behaviour.
That's not completely true. Calling a variadic function like printf()
without its prototype in scope yields UB. I'm not enough of a
language lawyer to parse 6.5.2.2 for you, but the fact that Annex J.2
is at pains to note when a function call without a function prototype
yields UB seems to indicate that there are cases where the behavior is
not undefined.

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gmail.com | don't, I need to know. Flames welcome.
Jan 13 '07 #5
sa*****@yahoo.co.in said:
Hi Everyone,

int main()
{
printf("not included stdio.h");
}

Yes, i haven't included stdio.h
and so you have called a variadic function without a valid prototype in
scope, as a result of which the behaviour of the program is undefined.

May I recommend "The C Programming Language", 2nd edition, by Brian W
Kernighan and Dennis M Ritchie? Reading it (slowly - its information
density is extremely high) will answer many of your questions.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jan 13 '07 #6
Christopher Benson-Manica <at***@ukato.freeshell.orgwrites:
santosh <sa*********@gmail.comwrote:
>Strictly according to the standard calling a function whose prototype
is not in scope leads to undefined behaviour.

That's not completely true. Calling a variadic function like printf()
without its prototype in scope yields UB. I'm not enough of a
language lawyer to parse 6.5.2.2 for you, but the fact that Annex J.2
is at pains to note when a function call without a function prototype
yields UB seems to indicate that there are cases where the behavior is
not undefined.
In C99, you can't call a function unless a declaration for it is
visible, but that declaration needn't be a prototype (i.e., it needn't
specify the parameter types). It *should*, and there's no good reason
not to, but non-prototype declarations are allowed for backward
compatibility.

For example:

void foo();

...

foo("hello", 42);

This is ok if the *definition* of foo() specifies that it returns
void, has two parameters of types char* and int, and that it's not
variadic.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 13 '07 #7
In article <ln************@nuthaus.mib.org>,
Keith Thompson <ks***@mib.orgwrote:
>In C99, you can't call a function unless a declaration for it is
visible, but that declaration needn't be a prototype
In C90 and earlier, if you call a function without a declaration it
will be assumed to return int, and its arguments will be subject to
the default promotions, and it will be assumed to be non-variadic
(variadic functions might have a different calling convention).

In practice, most compilers by default just warn about undeclared
functions, and things often work unless the return type is a
floating-point number or (on systems with ints and pointers of
different size) a pointer. It's a really bad idea to rely on it
though, because it may work on one system but not another, so
take note of compiler warnings!

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Jan 14 '07 #8
In article <11**********************@11g2000cwr.googlegroups. com>
<sa*****@yahoo.co.inwrote:
>... i haven't included stdio.h and my compiler would generate a
warning and would assume that it would return a int, my question is how
does the linker manage to link the function invocation to the proper
printf function?
Some have described the process by which particular specific linkers
happen to -- by "designed-in luck", as it were, although whether that
is "good luck" or "bad luck" is something of a matter of opinion --
make your call to printf() to a printf() routine in a library.

At least one person has noted that the behavior is officially
undefined.

There are some (rare) implementations on which the linker does
*not* manage to link your call to a library printf. So asking how
it did manage presupposes that you do not have such an implementation
-- it is a little like asking why sheep are white. (White sheep
are white for various reasons, but black sheep do exist.)
and does including a header file having function prototype help the
linker in any way?
It might. It might not. These things depend on the implementation.
Consider C++ for a moment, and note that C++ compilers commonly
use a technique called "name mangling", in which source-code function
names are replaced with link-time "mangled" names that encode the
*type* of the function as well as the original name. There is no
reason a C compiler could not do the same thing, so that:

int foo(void);
...
result = foo();

causes the linker to search for a name like i$foo$v. Including
stdio.h, which has to declare "printf" as having type int(const
char *,...) might tell the compiler to cause the linker to search
for i$printf$V.pc; but failure to include that header would leave
the compiler searching for i$printf$pc, so that the link would
fail.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Jan 15 '07 #9
Chris Torek wrote:
Consider C++ for a moment, and note that C++ compilers commonly
use a technique called "name mangling", in which source-code function
names are replaced with link-time "mangled" names that encode the
*type* of the function as well as the original name. There is no
reason a C compiler could not do the same thing, so that:

int foo(void);
...
result = foo();

causes the linker to search for a name like i$foo$v. Including
stdio.h, which has to declare "printf" as having type int(const
char *,...) might tell the compiler to cause the linker to search
for i$printf$V.pc; but failure to include that header would leave
the compiler searching for i$printf$pc, so that the link would
fail.
While name mangling is not prohibited, it is considerably more
difficult to implement in C, since function prototypes are not
required. There is nothing preventing a program from doing this:

a.c:
int (*get_puts(void))()
{
extern int puts();
return &puts;
}

b.c:
extern int (*get_puts(void))();
int main(void)
{
(*get_puts()) ((const char *) "Hello, world!");
}

When a.c is compiled, the compiler cannot know which types of arguments
puts expects. It may have special knowledge for the standard library
functions, but I could just as easily have used a user-defined function.

Jan 15 '07 #10
>Chris Torek wrote:
>... There is no reason a C compiler could not do [C++-like name mangling]
In article <11*********************@v45g2000cwv.googlegroups. com>
Harald van Dijk <tr*****@gmail.comwrote:
>While name mangling is not prohibited, it is considerably more
difficult to implement in C, since function prototypes are not
required.
Yes, I actually considered that but decided to omit details from
the sketch I posted.

The trick is that you can declare a function with prototype entirely
omitted:

/* optional: include "extern" keyword */ T func();

or with a full prototype:

/* extern */ T func(T1 arg1, T2 arg2, T3 arg3);

but not with any sort of "partial prototype". Moreover, a prototype
is always required if the function is variadic. Given the syntax I
suggested -- type-code, $, function-name, $, "V." for variadic, then
a sequence of type-codes separated by "$" signs, the linker would be
obligated to match a compiler reference of:

i$puts

to an actual:

i$puts$pc

symbol. However, i$puts$pi -- int puts(int *) -- would not match
to i$puts$pc -- int puts(char *). (Note that I also dropped "const"
in this particular notation. I am not sure off-hand whether it
would be OK to require const and volatile qualifiers to match.)

Because prototypes are required for variadic functions, "i$printf"
would not match "i$printf$V.pc", even though "i$puts" does match
"i$puts$pc".

The linker algorithm, in this notation, is more or less:

/*
* Test for function call symbol match.
* Return true if ref (a reference) matches def (a definition).
* The arguments may be modified temporarily.
*/
int function_matchp(char *ref, char *def) {
int ndollar = count_char(ref, '$');

if (ndollar == 1) {
/*
* The reference did not use a prototype, so we match
* any non-variadic function with the same name and
* return type.
*/
char *args;

args = find_arguments(def); /* roughly, two strchr()s for '$' */
if (args == NULL)
panic("function_matchp");
if (strncmp(args, "V.") == 0) /* def says it's variadic */
return 0; /* can't match without a prototype */

/* match against just the type and name */
if (strncmp(ref, def, args - def) != 0)
return 0;
if (warningcontrol.sloppy_match)
warn("matched non-prototyped call to %F to %F\n", ref, def);
return 1;
}

/*
* Reference included a prototype, so go for exact match.
*/
return strcmp(ref, def) == 0;
}
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Jan 15 '07 #11
Chris Torek wrote:
Chris Torek wrote:
... There is no reason a C compiler could not do [C++-like name mangling]

In article <11*********************@v45g2000cwv.googlegroups. com>
Harald van Dijk <tr*****@gmail.comwrote:
While name mangling is not prohibited, it is considerably more
difficult to implement in C, since function prototypes are not
required.

Yes, I actually considered that but decided to omit details from
the sketch I posted.

The trick is that you can declare a function with prototype entirely
omitted:

/* optional: include "extern" keyword */ T func();

or with a full prototype:

/* extern */ T func(T1 arg1, T2 arg2, T3 arg3);

but not with any sort of "partial prototype". Moreover, a prototype
is always required if the function is variadic. Given the syntax I
suggested -- type-code, $, function-name, $, "V." for variadic, then
a sequence of type-codes separated by "$" signs, the linker would be
obligated to match a compiler reference of:

i$puts

to an actual:

i$puts$pc

symbol. However, i$puts$pi -- int puts(int *) -- would not match
to i$puts$pc -- int puts(char *).
That would be possible.
(Note that I also dropped "const"
in this particular notation. I am not sure off-hand whether it
would be OK to require const and volatile qualifiers to match.)
The intent is that it is not allowed, and this intent is expressed in
the footnote attached to 6.2.5p25, but the normative text does not
state this (hence the cast in my example).
Because prototypes are required for variadic functions, "i$printf"
would not match "i$printf$V.pc", even though "i$puts" does match
"i$puts$pc".

The linker algorithm, in this notation, is more or less:
That's unnecessarily complicated. :) A compiler that sees a definition
of a function compatible with an unprototyped declaration may choose to
emit this function under two different names. Using memcpy because of
the trivial implementation, the compiler would compile

void *memcpy(void *restrict s1, const void *restrict s2, size_t n)
{
return memmove(s1, s2, n);
}

into

..extern pv$memcpy
pv$memcpy:
..extern pv$memcpy$pv$pv$i
pv$memcpy$pv$pv$i:
jmp memmove

This way, the linker would not need any knowledge of the meaning of the
dollar signs, and the logic to detect whether a function is compatible
with an unprototyped declaration must already be present in the
compiler anyway.

Jan 16 '07 #12
Kenny McCormack wrote:
In article <11**********************@11g2000cwr.googlegroups. com>,
<sa*****@yahoo.co.inwrote:
Hi Everyone,

int main()
{
printf("not included stdio.h");
}

Yes, i haven't included stdio.h and my compiler would generate a
warning and would assume that it would return a int, my question is how
does the linker manage to link the function invocation to the proper
printf function?
and does including a header file having function prototype help the
linker in any way?

The droids will tell you that this is undefined behavior, for all the
usual drecky reasons.
I have literally seen this sort of thing cause program crash. On some
compilers, the calling convention will tell the compiler how to unpile
the stack. If you compile with an option to (for instance) change who
does the pushing and/or popping or to pass the values in registers,
then the program can crash (or do anything else it wants to).

If you write crappy code, expect a crappy result. It may not
necessarily cause demons or Scott Nudds to come flying out of your left
nostril, but it might fetch a bunch of lawyers from the elevator.

Jan 16 '07 #13
"user923005" <dc*****@connx.comwrites:
Kenny McCormack wrote:
>In article <11**********************@11g2000cwr.googlegroups. com>,
<sa*****@yahoo.co.inwrote:
int main()
{
printf("not included stdio.h");
}

The droids will tell you that this is undefined behavior, for all the
usual drecky reasons.

I have literally seen this sort of thing cause program crash. On some
compilers, the calling convention will tell the compiler how to unpile
the stack. [...]
As far as I know, though, the lack of terminating new-line on the
program's output really is drecky as a reason for undefined
behavior, beyond the mundane possibility of the line not
appearing at all.
--
"Am I missing something?"
--Dan Pop
Jan 16 '07 #14
Ben Pfaff said:
"user923005" <dc*****@connx.comwrites:
>Kenny McCormack wrote:
>>In article <11**********************@11g2000cwr.googlegroups. com>,
<sa*****@yahoo.co.inwrote:
int main()
{
printf("not included stdio.h");
}

The droids will tell you that this is undefined behavior, for all the
usual drecky reasons.

I have literally seen this sort of thing cause program crash. On some
compilers, the calling convention will tell the compiler how to unpile
the stack. [...]

As far as I know, though, the lack of terminating new-line on the
program's output really is drecky as a reason for undefined
behavior, beyond the mundane possibility of the line not
appearing at all.
Um, the reason for the undefined behaviour was the omission of a prototype
for a variadic function.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Jan 16 '07 #15
Richard Heathfield <rj*@see.sig.invalidwrites:
Ben Pfaff said:
>"user923005" <dc*****@connx.comwrites:
>>Kenny McCormack wrote:
In article <11**********************@11g2000cwr.googlegroups. com>,
<sa*****@yahoo.co.inwrote:
int main()
{
printf("not included stdio.h");
}

The droids will tell you that this is undefined behavior, for all the
usual drecky reasons.

I have literally seen this sort of thing cause program crash. On some
compilers, the calling convention will tell the compiler how to unpile
the stack. [...]

As far as I know, though, the lack of terminating new-line on the
program's output really is drecky as a reason for undefined
behavior, beyond the mundane possibility of the line not
appearing at all.

Um, the reason for the undefined behaviour was the omission of a prototype
for a variadic function.
That's another reason, and the most obvious one, but C89 and C99
both clearly state that, for text streams:

Whether the last line requires a terminating new-line
character is implementation-defined.
--
Just another C hacker.
Jan 16 '07 #16
Ben Pfaff wrote:
>
.... snip ...
>
As far as I know, though, the lack of terminating new-line on the
program's output really is drecky as a reason for undefined
behavior, beyond the mundane possibility of the line not
appearing at all.
Well, isn't that undefined behaviour. What if that final line was:

"Internal error - ignore previous results".

in a medical treatment recommendation system.

--
"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>
Jan 16 '07 #17
CBFalconer <cb********@yahoo.comwrites:
Ben Pfaff wrote:
>>
... snip ...
>>
As far as I know, though, the lack of terminating new-line on the
program's output really is drecky as a reason for undefined
behavior, beyond the mundane possibility of the line not
appearing at all.

Well, isn't that undefined behaviour. What if that final line was:

"Internal error - ignore previous results".

in a medical treatment recommendation system.
Yes, it's undefined behavior. The "drecky" part is that the C
standard doesn't constrain behavior more tightly. It would be
perfectly reasonable in my opinion if it said something like "If
a text stream does not end in a new-line, the implementation may
drop the line or add a new-line itself" instead of making it so
wide-ranging.
--
"We put [the best] Assembler programmers in a little glass case in the hallway
near the Exit sign. The sign on the case says, `In case of optimization
problem, break glass.' Meanwhile, the problem solvers are busy doing their
work in languages most appropriate to the job at hand." --Richard Riehle
Jan 16 '07 #18
In article <WM******************************@bt.com>,
Richard Heathfield <rj*@see.sig.invalidwrote:
....
>Um, the reason for the undefined behaviour was the omission of a prototype
for a variadic function.
Correct. The other is just in the category of "You may not see the
output", not in the "UB" category.

Jan 17 '07 #19

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Michael R Seefelt | last post by:
I have written a simple C-program that loads a Python Function that connects to a PostgreSQL database> When I only load and execute the Python function all works OK. If I call the Python function a...
2
by: Eshrath | last post by:
Hi, What I am trying to do: ======================= I need to form a table in html using the xsl but the table that is formed is quite long and cannot be viewed in our application. So we are...
5
by: Luke | last post by:
Built-in functions don't bind to classes like regular functions. Is this intended? (I do notice that the Python Reference Manual sec 3.2 under "Class Instance" refers to a "user-defined...
2
by: Ciko | last post by:
Still not clear to me: why whe use <stdio.h> I haven't link stdio library (in linking stage) while if I use something of <math.h> I must link this library? Thanks in advance.
11
by: talk | last post by:
hi,guy i have a question. are the functions in <stdio.h> system calls provided by operation system? if so, i want to know how C implements that we can call system calls by using the functions in...
9
by: liaoo | last post by:
Dear all, I have a question about using cout<<... In standard C, I can use printf("%x",...) to print "hex" number. But in Watcom C++, when using cout<<, I got the "decimal" representation ! ...
1
by: Robert Dodier | last post by:
Hello, Sorry for asking what must be a FAQ, but I wasn't able to find the answer. I have an XML document fragment which I want to store as a text string. I want a function to convert any XML...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.