Search code examples
c++name-lookup

How to avoid function name conflict in a C library?


I'm programming a serial port on Unix, and I'm using the header file unistd.h. It contains the function:

read(int fd, void *buf, size_t count)

I'm making a class to call this function, and one of the methods in my class is also called read() to read one character. But when I compile, it says it cannot identify the function read() from unistd.h. If I was using C++, I could just add :: to resolve library conflict. How to resolve a library conflict when I'm using C++ and calling C library functions?

Later when a developer uses my library it would be simple and neat as follows:

Serial serial;
serial.read();

My class name is Serial and contains the method read(), which itself calls the function read() from unistd.h.


Solution

  • If I was using C++, I could just add :: to resolve library conflict.

    But you are using C++. Just because you include a header that contains C API, it doesn't mean the translation unit stops being a C++ translation unit. If the header is designed to play nice with C++, then its contents are still put in the global namespace (and unistd.h can be included in a C++ translation unit just fine).

    This means ::read will resolve to the C library function declared by unistd.h. You can use it just fine within Serial::read. Those are different functions to a C++ compiler. Just disambiguate the name inside the member function, since unqualified name lookup would have to find the member inside class scope.