Skip to content

Instantly share code, notes, and snippets.

@terryoy
Last active December 10, 2015 18:38
Show Gist options
  • Save terryoy/4475888 to your computer and use it in GitHub Desktop.
Save terryoy/4475888 to your computer and use it in GitHub Desktop.
Compile C program under linux
$ vi hello.c
# #include <stdio.h>
#
# int main() {
# printf("Hello world!\n");
# exit(0);
# }
$ gcc -o hello hello.c
hello.c: In function ‘main’:
hello.c:5:3: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default]
$ ./hello
Hello, world!
$ vi fred.c
# #include <stdio.h>
#
# void fred(int arg) {
# printf("fred: you have passed %d\n", arg);
# }
$ vi bill.c
# #include <stdio.h>
#
# void bill(char *arg) {
# printf("bill: you have passed %s\n", arg);
# }
$ gcc -c fred.c bill.c
$ ls *.o
bill.o fred.o
$ vi lib.h
# /* This is lib.h. It declares the functions fred and bill for users */
#
# void fred(int arg);
# void bill(char *arg);
$ vi program.c
# #include "lib.h"
#
# int main() {
# bill("Hello World!");
# fred(123);
# return 0;
# }
$ gcc -c program.c
$ gcc -o program program.o fred.o bill.o
$ ./program
bill: you have passed Hello World!
fred: you have passed 123
# create a static library
$ ar crv libfoo.a fred.o bill.o
a - bill.o
a - fred.o
$ ls libfoo.a
libfoo.a
$ ranlib libfoo.a
# linking static library
$ gcc -o program1 program.o libfoo.a
$ ls program1
program1
# list a program's neccessary share libraries
$ ldd program1
linux-gate.so.1 => (0xb7727000)
libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xb756a000)
/lib/ld-linux.so.2 (0xb7728000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment