Exposing functions instead of constants for describing library features

StackOverflow https://stackoverflow.com/questions/23587855

  •  19-07-2023
  •  | 
  •  

Pregunta

I've noticed that in a lot of library, version informations, as well as informations on the availability of special features that may differ or be absent depending on the build, are made accessible to client applications not by a constant, but by a function call returning a constant, e.g.:

const char *libversion(void) {
    return "0.2";
}

bool support_ssl(void) {
    return LIB_SSL_ENABLED; /* whatever */
}

instead of simply:

const char *libversion = "0.2";
bool support_ssl = LIB_SSL_ENABLED;

Is there a practical reason for doing this, or is it only some kind of convention?

¿Fue útil?

Solución

Is there a practical reason for doing this, or is it only some kind of convention?

I'd say both…

A practical reason I see for this, is that when you distribute your library, your users install a compiled version of it as a shared object, and access its data using the header. If the constant is accessible through a function, its prototype is declared in the header, but the value is defined in the compilation unit, linked in the shared object file. Edit: I'm not saying it's not possible, but a good reason for doing so is to keep the possibility to keep the API stable, while switching from a constant value to a calculated value for a given function, cf reason #3.

Another practical reason I can see is that you could access that API using some sort of "middleware", like corba, that enables you to access functions, but not constants (please be kind with me if I'm wrong about that particular point, I haven't done any CORBA in 10 years…).

And in the end, it's somehow good OOP convention, the header file being a pure functional interface, and all the members being encapsulated enabling a full decoupling of the inner workings of the library and the exposed behaviour.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top