Yui Yui - 11 months ago 48
C++ Question

Preprocessor identifier in front of function declarations in a header file

I was reading a header file and I noticed that the programmer has put a preprocessor identifier in front of the return values of functions in their declarations, as following.

#ifndef SAMPLE_API
#define SAMPLE_API


namespace SampleName
SAMPLE_API bool api_function();

What's the purpose of it and how does it work?

Edit: I am reading
from the IMGUI project.

Answer Source

By defining SAMPLE_API (on your compiler command line, in your Makefile / IDE environment etc.), you could add something to each function declaration in this header.

If you did not define SAMPLE_API, the first couple of lines...

#ifndef SAMPLE_API
#define SAMPLE_API

...make sure that SAMPLE_API is "defined away", i.e.

SAMPLE_API bool api_function();

...is preprocessed to...

bool api_function();

...so "nothing happens" (instead of "syntax error" when the compiler runs into SAMPLE_API and does not know what to do with it).

The usual reason for a construct like this SAMPLE_API symbol is to handle symbol export / import when building / using a library for Windows.

You would define SAMPLE_API to...

  • __declspec(dllexport) when building a library for Windows,
  • __declspec(dllimport) when using a library for Windows,

...so the symbols for the functions in question get exported / imported as necessary.

There are other things that could be done with such a preprocessor symbol (like deprecating functions, so that the linker will warn if they are being used), or other platform-specific stuff. But I would guess you're looking at dllexport / dllimport plumbing here.