我有两个文件。 sim.c 和 devices.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个错误
未定义对&quot; device_one&#39;的引用
未定义引用&quot; device_two&#39;
未定义对&quot; device_three&#39;
答案 0 :(得分:1)
错误表明您在编译devices
(包含sim.c
)时未与main
模块建立关联。您可以编译为:
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)