1

I would like to force an error or warning if I call a certain function from a third-party lib because I want to avoid needing reviews to make sure we do not call that function.

Google gives me very old StackOverflow answers to that problem at the top (e.g. Can I force a compiler error if certain functions are called?) which are based on adding #defines or #deprecated hints in the code which are based on preprocessing, but to avoid any weird issues with the naming there I was wondering whether there is any modern possibility to actually tell the linker that I want to link against library libfoo, but please error out if someone in my code links against a specific call in libfoo.

NOTE: This is not meant as a security protection against a malevolent actor, I only want to automate the process of detecting that we call that function by accident.

Blutkoete
  • 408
  • 3
  • 12
  • 1
    Did you try making a copy of the library's header file where the function is declared, removing the declaration and putting the altered header's directory first in the compiler's search path for includes? – Sam Varshavchik Jun 12 '23 at 12:07
  • 1
    ^ or at least mark them as `deprecated` to get warnings automatically. – πάντα ῥεῖ Jun 12 '23 at 12:08

2 Answers2

1

Sure, there are many ways of doing that.

If you want to do this during compile time, before runtime, you can use static_assert(condition, message). This is the the cleanest and modernist way thus far. Here is some info on that: Link. It is pure C++, no library necessary.

Example:

void foo(int a)
{
    static_assert(a > 5, "Too big!");
}

If you want to get it during runtime, you can throw exceptions throw runtime_error("Example");.

Hope that helps.

Amolgorithm
  • 697
  • 2
  • 20
0

You could use attributes deprecated or warning("message") to diagnose this at compile time:

$ cat tmp.c
__attribute__((warning("do not use me"))) void foo() {}

int main() { foo(); return 0; }

$ gcc tmp.c
tmp2.c: In function ‘main’:
tmp2.c:2:14: warning: call to ‘foo’ declared with attribute warning: do not use me [-Wattribute-warning]

This is a preferred approach as it will allow to diagnose errors early and with precise source code location.

On Linux you can also use a .gnu.warning section to emit warning at link time:

$ cat foo.c
void foo() {}

static const char foo_warning[] __attribute__((used,section(".gnu.warning.foo"))) = "do not use me";

$ cat main.c
void foo();

int main() { foo(); return 0; }

$ gcc foo.c main.c
/usr/bin/ld: /tmp/ccPfdczm.o: in function `main':
main.c:(.text+0xe): warning: do not use me
yugr
  • 19,769
  • 3
  • 51
  • 96