david_10001
david_10001

Reputation: 492

How to use printf() without any libraries in C?

I am programming a Teensy micro-controller as a part of a C course and am trying to work out the value of one of my integer variables. I have an integer variable called Contrast, which is initialised to the value of a constant defined as a hexadecimal number at the beginning of the .c file:

#define LCD_DEFAULT_CONTRAST    0x3F 
int Contrast = LCD_DEFAULT_CONTRAST;

I am trying to investigate how this Contrast value is stored and displayed, if it shows up as 63 or 0x3F, and if they are interchangeable. I tried to use:

printf("%d", Contrast);

to print out the Contrast value to the terminal and I got the error implicit declaration of function 'printf'. I thought printf() was part of the built-in C library, so I am confused why this is not working.

Can anyone please tell me how I print the value of this variable to the screen?

Upvotes: 1

Views: 1908

Answers (2)

printf() is declared in standard library header <stdio.h>.

You have to #include <stdio.h> to use printf(). It is a library call, much like all other library calls in C..

Upvotes: 1

Petr Skocik
Petr Skocik

Reputation: 60058

The implicit declaration error just means your compiler proper doesn't have a declaration for printf. Unless you're also getting a linker error, the linker (linking usually follows compilation, unless you pass -c to disable it) is probably slapping the standard lib right on, in which case you can simply solve your warning by including stdio.h or less preferably by declaring int printf(char const*, ...);.

If you trully don't have the standard lib, you'll need to convert the integer to a string manually with something like:

int n = 42;
char buf[20];
char *end = buf+(sizeof(buf)-1), *p = end;
*p--=0;
if(n==0) *p=='0';
else{
    while(n){
        printf("%d\n", n%10);
        *p--=n%10+'0'; 
        n/=10;
    }
    p++;
}

and then pass it to your system's raw IO routine for which you'll need to have set up the system-entering assembly.

If you don't have a system, it'd be even more technical, and you probably wouldn't be asking this question.

Upvotes: 4

Related Questions