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
,因爲我相信我正確地定義它,包括它。我究竟做錯了什麼?
完美解決方案。我幾年沒有編寫C++,所以我試圖回到事物的擺動。再過8分鐘,我會將這個答案標記爲解決方案。 – drjrm3