undefined reference to close(int)

I use Qt creator to compile a program which using Ubuntu socket library. In order to close the socket, the 'close' function defined in unistd.h is used.

First the strange thing is that if I only include unistd.h in my .cpp file, the g++ always say:

error: 'close' was not declared in this scope

After googling and checking for the man page, I declared the following line to resolve this problem.

int close(int fd);

However, now the new problem is in the linking stage. g++ says:

undefined reference to close(int)

Oh...this is kind of weird in my first thought. After googling so many articles, finally I resolved this problem by adding these lines:

#ifdef __cplusplus
   extern "C" {
#endif
int close(int fd);
#ifdef __cplusplus
}
#endif

OK. Now I leared that 'close' function is a C function, so we must declare it as extern "C".

留言

熱門文章