James Aflred
James Aflred

Reputation: 97

Undefined reference to functions C

I downloaded a library from here. I added the header file in my program but when I try to access the functions of this header file, I get error:

undefined reference to the function for u_open() and u_accept(). I tried to compile the .c files of this header file but I get this error:

undefined reference to main.

I tried everything in my knowledge to solve this issue, but couldn't solve it. Here is the program.

#include "uici.h"
int main()
{
char client[50];
char buf[1024];

u_port_t portnumber;
portnumber=48625;

int fd = u_open(portnumber);

int communFd = u_accept(fd,client,50);

perror("Opened");

fprintf(stderr,"\nComun fd is %d\n\n\n",communFd);

read(communFd,buf,1024);

write(STDOUT_FILENO,buf,1024);

fprintf(stderr,"\n\nReading complete\n");
return 0;
}

What can I do to solve this problem?

Regards

Upvotes: 0

Views: 3267

Answers (3)

sheu
sheu

Reputation: 5763

Your header file uici.h declares the functions you're calling in main() (u_open() and u_accept()), but not their implementations, which are in the source files. When the linker tries to create the entire program, it then complains that the implementations can't be found.

The solution is to link all the files together when creating the actual program binary. When using the g++ frontend, you can do this by specifying all the source files together on the command line. For example:

g++ -o main main.c uici.c

will create the main program called "main", assuming that the implementations you need are in uici.c.

edit: In the case you're linking against a prebuilt library for uici, you'll need to specify to the frontend that the library is needed for linking, e.g. with:

g++ -o main main.c -luici

Upvotes: 1

sr01853
sr01853

Reputation: 6121

Use any of these flags while compiling with gcc

-I <searchpath to include files>
-L <searchpath to the lib file>
-l<thelibname>

Ex:

  gcc -o myprogram -lfoo -L/home/me/foo/lib myprogram.c

This will link myprogram with the static library libfoo.a in the folder /home/me/foo/lib

Upvotes: 0

Deepankar Bajpeyi
Deepankar Bajpeyi

Reputation: 5859

You need to link the library when using gcc like :

gcc nameofprgram.c -l<library>

Upvotes: 0

Related Questions