4

I am using libevent now:

#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdio.h>
#include <event2/event.h>

struct event_base *base;
int PORT = 9999;
int BACKLOG = 5;

int create_bind_listen()
{
    struct sockaddr_in my_addr;
    int yes = 1;
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
    memset(&my_addr, 0, sizeof(struct sockaddr_in));
    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(PORT);
    my_addr.sin_addr.s_addr = INADDR_ANY;
    bind(sock, (struct sockaddr*)&my_addr, sizeof(struct sockaddr));
    listen(sock, BACKLOG);
    return sock;
}

void cb_func(evutil_socket_t fd, short what, void *arg)
{
    printf("%d\n", fd);
}

int main()
{
    int sock = create_bind_listen();
    struct event *ev;
    base = event_base_new();
    /*   */
    ev = event_new(base, sock,
                   (short)EV_READ|EV_PERSIST,
                   cb_func, NULL);
    event_add(ev, NULL);
    event_base_dispatch(base);
    return 0;
}

When I compile with that:

gcc -Wall main.c -levent -levent_core

Error happened:

/tmp/cc9x1mMj.o: In function `main':
main.c:(.text+0x11b): undefined reference to `event_new'
collect2: ld returned 1 exit status

How could I fix this?

Thank you !

kaitian521
  • 548
  • 2
  • 10
  • 25

3 Answers3

7

You need to specify the directory where your .a. files are located with the -L option:

gcc -Wall main.c -L. -levent -levent_core
mtripp100
  • 231
  • 1
  • 5
  • And seems the order of the arguments matters too. For example, compilation would fails in the following input: `gcc -Wall -L. -levent -levent_core main.c` – Xiaofan Hu Oct 06 '16 at 03:12
2

FWIW I needed a newer version of libevent then this went away for me... libevent-2.1.8-stable worked. (it needs libevent2 basically).

Maybe can install libevent2-devel package instead of libevent-devel package.

rogerdpack
  • 62,887
  • 36
  • 269
  • 388
  • getting the latest version was very helpful in combination of https://superuser.com/questions/738829/attempting-to-install-tmux-on-centos-6-x-fails-with-error-evbuffer-eol-lf-und – Gilad M Feb 01 '18 at 19:19
0
c++ -std=c++17 -O3   'first 3.cpp' `pkg-config --cflags --libs libevent libkqueue libevent_pthreads`  -o t