3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

systemdのassert_returnマクロ

Posted at

systemdにはassert_returnというマクロがある。assertに失敗したら、指定エラー値でreturnするだけなのだが、こういうのがあるとコーディングスタイルが統一されて良いと思う。

使い方はこんな感じ:

src/journal/journal-send.c
_public_ int sd_journal_printv(int priority, const char *format, va_list ap) {

        /* FIXME: Instead of limiting things to LINE_MAX we could do a
           C99 variable-length array on the stack here in a loop. */

        char buffer[8 + LINE_MAX], p[11]; struct iovec iov[2];

        assert_return(priority >= 0, -EINVAL);
        assert_return(priority <= 7, -EINVAL);
        assert_return(format, -EINVAL);

CODING_STYLEに書いてあるが、公開APIでは引数チェックが義務付けられていて、assert_returnはその道具の一つらしい。

定義はこんな感じ:

src/shared/macro.h
# define assert_return(expr, r)                                          \
        do {                                                            \
                if (_unlikely_(!(expr))) {                              \
                        log_assert_failed_return(#expr, __FILE__, __LINE__, __PRETTY_FUNCTION__); \
                        return (r);                                     \
                }                                                       \
        } while (false)

_unlikely_はLinuxではお馴染みのあれ。__PRETTY_FUNCTION____FUNCTION__より情報量のある名前を返してくれるらしい。

試しに使ってみるとこんな感じ:

$ cat pretty_function.c
# include <stdio.h>

int main(void)
{
  printf("%s\n", __FUNCTION__);
  printf("%s\n", __PRETTY_FUNCTION__);
  return 0;
}
$ ./a.out              
main
int main()

6.45 Function Names as Strings を読む感じだと、C++の方で力を発揮しそうですね。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?