2014-01-14 52 views
0

我已经看到了这个网站的标准Undefined Reference to线程,但我不认为它解决了我的问题。我没有在我的.cpp文件中放置标题警卫,但仍然获得对用户定义函数的未定义引用。这是我的文件:未定义参考用户定义的函数

(1)pth_funs.h

// hello from thread <pid> 
void* hello(void* ptr); 

(2)pth_funs.cpp

#include <stdio.h> 

void* hello(void *ptr) 
{ 
    char *message; 
    int pid = (long) ptr; 
    printf("Hello from thread %i\n", pid); 
} 

(3)structs.h

#ifndef STRUCTS_H 
#define STRUCTS_H 
struct grd_str { 
    long nx; 
    long ny; 
    long natoms; 
    char** atnames; 
    double* xs; 
    double* ys; 
    double** fs; 
    double** xyzs; 
}; 
#endif 

(4- )fio.h

#ifndef FIO_H 
#define FIO_H 
#include <iostream> 
#include <string.h> 
#include "structs.h" 

void read_grd(std::string, grd_str); 

#endif 

(5)fio.cpp

#include <string.h> 
#include "structs.h" 
#include "fio.h" 

void read_grd(std::string fname, grd_str &grd) 
{ 
    grd.nx = 10; 
    grd.ny = 10; 
} 

(6),最后,xdriver.cpp

#include <iostream> // needed for cout, endl, etc 
using namespace std; // needed for cout, endl, etc 
#include <pthread.h> // needed for pthreads 
#include <string.h> // string handling 

#include "pth_funs.h" // pthread function headers 
#include "structs.h" 
#include "fio.h" 

int main(int argc, char** argv) 
{ 
    // thread stuff 
    int nthreads = 4; 
    pthread_t rank[4]; 
    int iret[4]; 

    // file stuff 
    string base_dir = "D:\\cygwin64\\home\\Robert\\code\\C\\form_reconstruction\\data\\"; 
    string fname; 

    // topology stuff 
    int nx, ny; 
    double* xs; 
    double* ys; 
    double** fs; 
    grd_str grd; 

    for(long tid = 0; tid < nthreads; tid++) 
    { iret[tid] = pthread_create(&rank[tid], NULL, hello, (void*) tid); } 

    fname = base_dir; 
    fname.append("adf\\adf.6.grd"); 
    cout << "Filename: " << fname << endl; 

    read_grd(fname, grd); 
} 

我使用的是生成文件,其是如下编译此:

cc=g++ 
exe=create_grd.exe 

flags=-pthread 
hds= pth_funs.h fio.h structs.h 
objs= pth_funs.o fio.o 

all: create_grd.exe 

create_grd.exe: xdriver.cpp $(hds) $(objs) 
    $(cc) -o $(exe) $(objs) xdriver.cpp 

pth_funs.o: pth_funs.cpp pth_funs.h 
    $(cc) -c pth_funs.cpp $(flags) 

fio.o: fio.cpp fio.h 
    $(cc) -c fio.cpp $(flags) 

clean: 
    rm -rf *.o 

然而,在编译时,我得到

g++ -c pth_funs.cpp -lpthread 
g++ -c fio.cpp -lpthread 
g++ -o create_grd.exe pth_funs.o fio.o xdriver.cpp -lpthread 
/tmp/ccdaBayB.o: In function `main': 
xdriver.cpp:(.text+0x16f): undefined reference to `read_grd(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, grd_str)' 
collect2: ld returned 1 exit status 
make: *** [create_grd.exe] Error 1 

,但我不知道为什么我的主程序找不到read_grd,因为我相信我正确地定义它,包括它。我究竟做错了什么?

回答

1

你的宣言和read_grd定义没有匹配的参数。一个需要grd_str作为第二个参数,另一个需要grd_str&。由于xdriver.cpp包含fio.h,因此它会查看并尝试使用前一个函数,但链接程序无法在任何地方找到它的定义。有可能到头来你想改变fio.h您声明:

void read_grd(std::string, grd_str&); 

现在这个函数的定义是由fio.cpp提供。

+0

完美解决方案。我几年没有编写C++,所以我试图回到事物的摆动。再过8分钟,我会将这个答案标记为解决方案。 – drjrm3