How to avoid function name conflict in a C library?

Viewed 666

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.

2 Answers

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.

How to resolve library conflict when I'm using C++ and calling functions from C?

If you write C++, you typically use classes with member functions. And the compiler sees that a call is related to a given object, so you don't run in that conflict.

If you use "free functions" you can give these functions a own namespace and simply use the namespace in the call like serial::read();.

You also can add static functions to classes which will give them also a named scope without the need of creating objects from the class itself.

namespace serial_ns
{
int read( int, void*, size_t n){return 0;}
}

struct serial_struct
{
    static int read( int, void*, size_t n){return 0;}
};

class Serial
{
    public:
        int read( int, void*, size_t n ) { return 0; }
};

int main()
{
    char buf[5];
    read( 0, buf, 5); // call to c-library
    serial_ns::read( 0,buf,5);
    serial_struct::read( 0,buf,5);

    // with an object:
    Serial ser;
    ser.read( 0,buf,5);
}
Related