Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print to console (Linux) without the standard library (libc)

Tags:

c

linux

gcc

I'm not using the standard library, since my target x86 Linux distro is very limited.

#include <unistd.h>

void _start () {
      const char msg[] = "Hello world";
      write( STDOUT_FILENO, msg, sizeof( msg ) - 1 );
}

I want to print text to console, but I can't, is there any other way to do this. The code above wont work because it depends on standard library gcc Test.cpp -o Test -nostdlib

like image 452
nGs2225 Avatar asked Sep 03 '25 02:09

nGs2225


1 Answers

If you don't have libc, then you need to craft a write() system call from scratch to write to the standard output.

See this resource for the details: http://weeb.ddns.net/0/programming/c_without_standard_library_linux.txt

Code example from the above link:

void* syscall5(
    void* number,
    void* arg1,
    void* arg2,
    void* arg3,
    void* arg4,
    void* arg5
);

typedef unsigned long int uintptr; /* size_t */
typedef long int intptr; /* ssize_t */

static
intptr write(int fd, void const* data, uintptr nbytes)
{
    return (intptr)
        syscall5(
            (void*)1, /* SYS_write */
            (void*)(intptr)fd,
            (void*)data,
            (void*)nbytes,
            0, /* ignored */
            0  /* ignored */
        );
}

int main(int argc, char* argv[]) 
{
    write(1, "hello\n", 6);
    return 0;
}
like image 144
payne Avatar answered Sep 04 '25 23:09

payne