未定义 在 Linux 中线程时对函数的引用

Undefined Reference to function while threading in Linux

提问人: 提问时间:6/23/2018 更新时间:7/27/2020 访问量:326

问:

我查找了其他问题,以确保这不是重复的。

我有 3 个文件:

file1.h
file1.c
file2.c

file1.h 中有这样一行:

void *myFunction(void *vargp);

file1.c 具有:

#include <pthread.h>
#include "file1.h"    
void *myFunction(void *vargp)
    { 
        //do stuff
        return 0;
    }

file2.c 具有:

#include <pthread.h>
#include "file1.h"

int main()
{
    pthread_t thread_id;
    int t1; 
    t1 =  pthread_create(&thread_id, NULL, myFunction, NULL);
    pthread_join(thread_id, NULL);
    return 0;
}

我使用以下命令进行编译和链接:

gcc -pthread -o file2 file2.c

我收到以下错误:

file2.c:(.text+0xa64): undefined reference to `myFunction'
file2.c:(.text+0xa68): undefined reference to `myFunction'
Linux 多线程 POSIX 未定义参考

评论

0赞 txtechhelp 6/23/2018
您正在编译但引用 , ,然后提到 ....您确定您为所有内容都使用了正确的文件吗?myCode.cfile1.cfile2.cfile3.c
0赞 6/23/2018
@txtechhelp对不起,你解决了这个问题
0赞 txtechhelp 6/23/2018
跑步时会发生什么?gcc -pthread -o myCode file1.c file2.c
0赞 6/23/2018
@txtechhelp相同的错误

答:

0赞 user6552697 6/23/2018 #1

我提出了两个独立的解决方案,它们都有效:

  1. 这样做:gcc -pthread -o file2 file2.c file1.c
  2. 这样做:输入代码 file2.c 而不是#include "file1.c"#include "file1.h"

编辑:如果你有两个电源,你就不能做方法#2!

0赞 Shubham Jain 7/27/2020 #2

我在线程创建下面定义了我的线程函数,然后它工作正常