Reputation: 22270
I want to use from the file tester-1.c functions that I defined in libdrm.h and gave implementation in libdrm.c. The three files are on the same folder and use pthread functions.
Their include files are:
libdrm.h
#ifndef __LIBDRM_H__
#define __LIBDRM_H__
#include <pthread.h>
#endif
libdrm.c <- has no main()
#include <stdio.h>
#include <pthread.h>
#include "libdrm.h"
tester-1.c <- has teh main()
#include <stdio.h>
#include <pthread.h>
#include "libdrm.h"
The compiler error for libdrm.c says:
gcc libdrm.c -o libdrm -l pthread
/usr/lib/gcc/x86_64-linux-gnu/4.4.5/../../../../lib/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status
And the compiler errors for tester-1.c say:
gcc tester-1.c -o tester1 -l pthread
/tmp/ccMD91zU.o: In function `thread_1':
tester-1.c:(.text+0x12): undefined reference to `drm_lock'
tester-1.c:(.text+0x2b): undefined reference to `drm_lock'
tester-1.c:(.text+0x35): undefined reference to `drm_unlock'
tester-1.c:(.text+0x3f): undefined reference to `drm_unlock'
/tmp/ccMD91zU.o: In function `thread_2':
tester-1.c:(.text+0x57): undefined reference to `drm_lock'
tester-1.c:(.text+0x70): undefined reference to `drm_lock'
tester-1.c:(.text+0x7a): undefined reference to `drm_unlock'
tester-1.c:(.text+0x84): undefined reference to `drm_unlock'
/tmp/ccMD91zU.o: In function `main':
tester-1.c:(.text+0x98): undefined reference to `drm_setmode'
tester-1.c:(.text+0xa2): undefined reference to `drm_init'
tester-1.c:(.text+0xac): undefined reference to `drm_init'
tester-1.c:(.text+0x10e): undefined reference to `drm_destroy'
tester-1.c:(.text+0x118): undefined reference to `drm_destroy'
All these functions are defined in libdrm.c
What gcc commands should I use to make these files compile and link?
Upvotes: 3
Views: 11656
Reputation: 6548
To compile your .c
sources to object files, use GCC's -c
option. Then you can link the object files to an executable, against the required library:
gcc libdrm.c -c
gcc tester-1.c -c
gcc tester-1.o libdrm.o -o tester1 -lpthread
Doing compiling and linking in one go, as many others have suggested, works fine too. However, it's good to understand that the build process involves both of these stages.
Your build failed, because your translation modules (=source files) required symbols from each other.
libdrm.c
alone couldn't produce an executable, because it does not have a main()
function.tester-1.c
's linking failed, because the linker wasn't informed about the required symbols defined in libdrm.c
.With -c
option, GCC compiles and assembles the source, but skips linking, leaving you with .o
files, which can be linked into an executable or packaged into a library.
Upvotes: 11
Reputation: 3818
gcc tester-1.c libdrm.c -o tester1 -l pthread
You need to compile all the source files in one go rather than doing them individually. Either that or compile libdrm.c as a library and then link it with tester1.c when you compile that.
Upvotes: 1