在静态库中内联 class 方法
Inlining class methods inside a static library
在 this 问题中,答案指出要为静态库内联一个函数,该函数在 header 文件中声明为 inline
,在 extern
中声明为源文件。但是在 C++ 中,如果这样做,则会生成编译器错误 (Redeclaration of member is not allowed
)。编写函数的正确方法是什么,以便它的工作方式与 C post?
Header:
class Int64
{
uint64_t a;
public:
inline void flip() { a = ~a; }
};
来源:
extern void Int64::flip(); // redeclaration of member is not allowed
在 C++ 中,您可以将函数声明为 inline
只有当函数代码在编译时可用时(如果您真的想内联该函数代码)。所以你不能在编译后的静态库中实现函数body,当你使用这个静态库时,它是不可用的。如果这样做,此函数调用将类似于普通函数调用。
来自cppreference:
2) The definition of an inline function must be present in the
translation unit where it is accessed (not necessarily before the
point of access).
不过,您可以在静态库 header 中定义 inline
函数(如 header 唯一函数)。
顺便说一下,请记住 inline
只是一个建议。编译器将决定是否内联。这通常发生在您编译启用优化的代码时,但特别是当您不优化代码时,您通常会看到函数未内联。
例如,检查这个包含 2 个文件的小型静态库:
test.h:
#pragma once
inline int sum(int a, int b)
{
return a + b;
}
int sub(int a, int b);
test.cpp:
int sub(int a, int b)
{
return a - b;
}
当你使用这个库的时候,sum
会被内联,sub
会是一个普通的普通调用。请记住,您甚至可以在库 header 中将 sub
定义为 inline
(没有它的 body),它仍然像一个普通的函数调用。
在 this 问题中,答案指出要为静态库内联一个函数,该函数在 header 文件中声明为 inline
,在 extern
中声明为源文件。但是在 C++ 中,如果这样做,则会生成编译器错误 (Redeclaration of member is not allowed
)。编写函数的正确方法是什么,以便它的工作方式与 C post?
Header:
class Int64
{
uint64_t a;
public:
inline void flip() { a = ~a; }
};
来源:
extern void Int64::flip(); // redeclaration of member is not allowed
在 C++ 中,您可以将函数声明为 inline
只有当函数代码在编译时可用时(如果您真的想内联该函数代码)。所以你不能在编译后的静态库中实现函数body,当你使用这个静态库时,它是不可用的。如果这样做,此函数调用将类似于普通函数调用。
来自cppreference:
2) The definition of an inline function must be present in the translation unit where it is accessed (not necessarily before the point of access).
不过,您可以在静态库 header 中定义 inline
函数(如 header 唯一函数)。
顺便说一下,请记住 inline
只是一个建议。编译器将决定是否内联。这通常发生在您编译启用优化的代码时,但特别是当您不优化代码时,您通常会看到函数未内联。
例如,检查这个包含 2 个文件的小型静态库:
test.h:
#pragma once
inline int sum(int a, int b)
{
return a + b;
}
int sub(int a, int b);
test.cpp:
int sub(int a, int b)
{
return a - b;
}
当你使用这个库的时候,sum
会被内联,sub
会是一个普通的普通调用。请记住,您甚至可以在库 header 中将 sub
定义为 inline
(没有它的 body),它仍然像一个普通的函数调用。