【问题标题】:Thread function in separate file with pthread and make使用 pthread 和 make 在单独的文件中执行线程函数
【发布时间】:2018-11-08 10:15:07
【问题描述】:

当作为参数传递的线程函数位于单独的文件中时,使用pthread_create() 创建线程时,以下代码存在问题。在同一个文件中可以正常工作。

我有Main.c、ThreadFunction.h、ThreadFunction.c 和一个makefile。我猜问题出在makefile,但我就是想不通。

我的问题:

是不是因为ThreadFunction.o 目标文件不是用-pthread 制作的?如果这是为什么,你是怎么做到的?还是因为别的原因?

这是造成我的问题的代码:

Main.c

#include <stdio.h>
#include <pthread.h>
#include "ThreadFunction.h"

int main(int argc, char * argv[]) 
{
    pthread_t tid;
    int err;
    void *res;
    err = pthread_create(&tid, NULL, &ThreadFunction, "Argument from main");
    err = pthread_join(tid, &res);
    return 0;
}

ThreadFunction.h

static void *ThreadFunction(void *arg);

ThreadFunction.c

#include "ThreadFunction.h"
#include <stdio.h>
#include <pthread.h>

static void *ThreadFunction(void *arg)
{
    pthread_t id = pthread_self();
    printf("From thread: %s\n", (char *)arg);
    printf("Thread ID: %ld\n", id);
}

生成文件

LINK_TARGET = test.exe
OBJS = Main.o ThreadFunction.o
REBUILDABLES = $(OBJS) $(LINK_TARGET)
LIBS = -pthread

clean:
    rm -f $(REBUILDABLES)
    echo Clean done

all: $(LINK_TARGET)
    echo All done

$(LINK_TARGET) : $(OBJS)
    gcc -g -o $@ $^ $(LIBS)

$.o : $.cpp
    gcc -g -o $@ -c $<

Main.o : ThreadFunction.h
ThreadFunction.o : ThreadFunction.h

【问题讨论】:

  • 您的ThreadFunction 是静态的,这意味着它仅在文件范围内可用。

标签: c gcc makefile pthreads


【解决方案1】:

静态函数是模块本地的,对其他编译单元不可见。从其定义和声明中删除static。

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 2013-03-22
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    相关资源
    最近更新 更多