gpt4 book ai didi

无法从另一个文件中的函数创建线程

转载 作者:行者123 更新时间:2023-11-30 20:58:52 25 4
gpt4 key购买 nike

我有两个文件。 sim.cdevices.c

这是sim.c

...
#include "devices.h"

int main(int argc, char **argv) {
pthread_t *tid;

tid = (pthread_t *) malloc(sizeof(pthread_t) * 3);

// this is where I start the 3 threads located in devices.c
if (pthread_create(&tid[0], NULL, device_one, NULL)) {
exit(1);
}
if (pthread_create(&tid[1], NULL, device_two, NULL)) {
exit(1);
}
if (pthread_create(&tid[2], NULL, device_three, NULL)) {
exit(1);
}

// wait for 3 threads to finish
int i;
for (i = 0; i < 3; i++) {
if (pthread_join(tid[i], NULL)) {
exit(1);
}
}
}

这里是devices.c

...
#include "devices.h"

extern void *device_one(void *arg) {
printf("device one is called\n");
return NULL;
}

extern void *device_two(void *arg) {
printf("device two is called\n");
return NULL;
}

extern void *device_three(void *arg) {
printf("device three is called\n");
return NULL;
}

这是devices.h

#ifndef DEVICES_H
#define DEVICES_H

extern void *device_one(void *arg);
extern void *device_two(void *arg);
extern void *device_three(void *arg);

但是,当我编译时,我在 sim.c 下收到 3 个错误,说
对“device_one”的 undefined reference
对“device_two”的 undefined reference
对“device_two”的 undefined reference

最佳答案

这些错误表明您在编译 sim.c(其中包含 main)时未链接到 devices 模块。您可以编译为:

gcc sim.c devices.c -I.

或者您可以创建一个 makefile:

CC = gcc
CFLAGS = -I.
DEPS = devices.h
OBJ = sim.o devices.o
LDLIBS = -pthread

%.o: %.c $(DEPS)
$(CC) -c -o $@ $< $(CFLAGS)

sim: $(OBJ)
$(CC) -o $@ $^ $(CFLAGS) $(LDLIBS)

.PHONY: clean

clean:
rm -rf $(OBJ)

关于无法从另一个文件中的函数创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49308459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com