c - 单个文件的 undefined reference

标签 c linker pthreads undefined-reference

我从 StackOverflow 上的其他帖子中看到, undefined reference 错误意味着缺少定义,通常要修复它,必须在编译中链接文件。但我只编译一个文件。我收到函数 pthread_detachpthread_create 的错误。

/tmp/ccAET7bU.o: In function `sample_thread1':
foo.c:(.text+0x2a): undefined reference to `pthread_detach'

/tmp/ccAET7bU.o: In function `main':
foo.c:(.text+0x85): undefined reference to `pthread_create'

collect2: error: ld returned 1 exit status

代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <memory.h>
#include <signal.h>
#include <string.h>
#include <linux/unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <netinet/in.h>
#include <pthread.h>

pid_t gettid(void)
{
    return syscall(__NR_gettid);
}

void *sample_thread1(void *x_void_ptr)
{
    FILE *fp;
    int counter;

    pthread_detach(pthread_self());

    if((fp = fopen("thread_data.txt", "w")) == NULL)
    {
        printf("ERROR : Thread cannot open data file.\n");
        return;
    }   
    counter = 1;
    while(1);
    {
        fprintf(fp, "INFO : Thread1 id %d output message %10d\n",
                gettid(), counter);
        fflush(fp);
        counter++;
        sleep(1);
    }
    pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
    int counter;
    pthread_t sample_thread_t1;

    if(pthread_create(&sample_thread_t1, NULL, sample_thread1, NULL))
    {
        fprintf(stderr, "Error creating thread\n");
        exit(-1);
    }
    system("clear");

    counter = 1;
    while(1)
    {
        printf("INFO : Main Process Counter = %d\n", counter);
        counter++;
        sleep(1);
    }
    return(0);
} 

最佳答案

您必须使用 GCC 或 clang 的 -lpthread-pthread 选项将其与 pthread 库链接。

例子:

gcc your_file.c -o program -lpthread
# or gcc your_file.c -o program -pthread
# the same for clang

关于c - 单个文件的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30004893/

相关文章:

c - 不停止 gdb 中的所有线程

c - 编译 pthread 时出错,pthread create 表示多参数传递的结构类型错误

c - 如何在c中存储固定长度的字符串

c - 在 C 中 malloc'ing 多维数组

c - 编译/链接时强制指定函数链接到指定库

linker - 如何链接特定库( g++; libstdc++.so.5 和 libstdc++.so.6 )

c - If 语句使用 | 输出运算符(operator)

c - getchar 和 putchar

gcc - 使用 gcc 链接共享库

c++ - 非阻塞 pthread 停止 - 或者为什么 std::atomic_flag 会减慢我的代码