How to embed a function for release build only

// common.h
// This is foo function. It has a body.
__inline void foo() { /* something */ }

// a.cpp
#include "common.h" // for foo function
// Call foo

// b.cpp
#include "common.h" // for foo function
// Call foo

I would like to enable the foo function only when I create for release. I do not want to build in functions for assembly Debug.

I tried, but the linker errors annoyed me.
In this case, the function body is foodefined in the common.h header file.
so if i just do

//common.h
#if !defined(_DEBUG)
__inline
#endif
void foo() { /* something */ }

DebugA link error will be encountered in build. Because two modules are trying to enable common.h.
I am not going to solve it. Is it possible?

+3
source share
6 answers

, inline ( Microsoft __inline C - MSVC C99) , . - , - .

, inline, , . , , .

, inline, , ( , ). , ( C), :

  • static, ( , static inline).
  • ++ ( , )
  • , . , , , . , - , .

, .c, , ( , .c-, , , ). , , , . , , ( ), , ( ):

common.h:   //common.h   #ifndef COMMON_H   #define COMMON_H

#ifdef RELEASE
#define USE_INLINE
#define INLINE __inline
#else
#define INLINE
#endif

INLINE void foo(void);
#ifdef USE_INLINE
#include "foo.c"
#endif

#endif /* COMMON_H */

foo():

// foo.c
#ifndef FOO_C
#define FOO_C

#include <stdio.h>
#include "common.h"


INLINE void foo()
{
    printf("foo\n");
}

#endif /* FOO_C */

:

// main.c
#include<stdio.h>
#include "common.h"

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

, :

cl /DRELEASE main.c foo.c

foo() inline ( __inline ).

-:

cl  test.c foo.c

foo().

.

, , , , inline static .

, , , - inline, , , , . , .

, . , inline / ?

+5

"" :

#if !defined(_DEBUG) || defined(NDEBUG)
#define INLINE inline
#else
#define INLINE static
#endif

static .

< . GCC -wno-inline-functions -fno-inline-small-functions, , -O1 (, , -Os). .

, inline, .

+7
#ifdef RELEASE
#define INLINE __inline
#else
#define INLINE
#endif

// common.h
INLINE void foo() { /* something */ }

// a.cpp
#include "common.h" // for foo function
// Call foo

// b.cpp
#include "common.h" // for foo function
// Call foo

RELEASE . , , .

+4

. ( a.k.a. C-style), ( , ) . - . .

+3

. . _DEBUG , :

:

#ifndef _DEBUG
    __inline void foo() { /* something */ }
#else 
     //some alternative
#endif
+1

.

:

#ifdef RELEASE_BUILD_FLAG
  //Run inline function
#else
  //some alternative
#endif
0

Source: https://habr.com/ru/post/1784008/


All Articles