如何在 C++ 中定义全局函数?

发布于 2024-11-27 06:10:04 字数 126 浏览 2 评论 0原文

我想要一个不是类成员并且可以从任何类访问的函数。

我假设我必须 #include 声明该函数的头文件,但我不知道在哪里定义这样的全局函数。

首先是否有充分的理由反对拥有这样的功能?

I would like a function that is not a member of a class and is accessible from any class.

I assume I would have to #include the header file where the function is declared, but I don't know where to define such a global function.

Are there good reasons against having such a function in the first place?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

北音执念 2024-12-04 06:10:04

您需要一个主体(在 cpp 文件中):

int foo()
{
    return 1;
}

以及头文件中的定义/原型,该定义/原型将在使用该函数之前包含:

#ifndef MY_FOO_HEADER_
#define MY_FOO_HEADER_
    int foo();
#endif

然后在其他地方使用它:

#include foo.h
void do_some_work()
{
    int bar = foo();
}

或使用内联函数(不保证它会被内联,但对于小函数很有用,例如 foo):

#ifndef MY_FOO_HEADER_
#define MY_FOO_HEADER_
    inline int foo()
    {
        return 1;
    }
#endif

或者您可以滥用基于 C 风格标头的函数(因此这会出现在标头中,static 强制它存在于仅单个编译单元,但是您应该避免这种情况):

#ifndef MY_FOO_HEADER_
#define MY_FOO_HEADER_
    static int foo()
    {
        return 1;
    }
#endif

you need a body (in a cpp file):

int foo()
{
    return 1;
}

and a definition/prototype in a header file, which will be included before any use of the function:

#ifndef MY_FOO_HEADER_
#define MY_FOO_HEADER_
    int foo();
#endif

then using it somewhere else:

#include foo.h
void do_some_work()
{
    int bar = foo();
}

or use an inline function (doesn't guarantee it'll be inlined, but useful for small functions, like foo):

#ifndef MY_FOO_HEADER_
#define MY_FOO_HEADER_
    inline int foo()
    {
        return 1;
    }
#endif

alternatively you can abuse the C-style header based functions (so this goes in a header, the static forces it to exist in a single compilation unit only, you should avoid this however):

#ifndef MY_FOO_HEADER_
#define MY_FOO_HEADER_
    static int foo()
    {
        return 1;
    }
#endif
眸中客 2024-12-04 06:10:04

您所调用的全局函数通常称为自由函数,它们是一件好事

您可以像类的成员函数一样定义它,但在该类的范围之外。

double squared(double x) {
    return x*x;
}

您可以在头文件中使用 inline 关键字定义简单的函数,或者只是在头文件中声明它

double squared(double x);

并将实现(第一个示例)放入 *.cpp 文件中。

What you are calling global function is usually called a free function and they are A Good Thing.

You would define it just like a class' member function, but outside of that class' scope.

double squared(double x) {
    return x*x;
}

Simple functions you can define with the inline keyword in the header file, or just declare it there

double squared(double x);

and put the implementation (first example) into the *.cpp file.

守不住的情 2024-12-04 06:10:04

在头文件中:

// someheader.h
#ifndef MY_GLOBAL_FUN
#define MY_GLOBAL_FUN

void my_global_fun();    

#endif

在实现文件中: 在

#include "someheader.h"

void my_global_fun()
{
    // ...
}

需要该函数的其他文件中:

#include "someheader.h"

void f()
{
    my_global_fun();
}

像这样的自由函数很有用,并且没有太多反对使用它们的论点。根据您的用例,将这些函数放在特定的命名空间中可能是合适的,以避免与您可能使用的其他库发生名称冲突。

In a header file:

// someheader.h
#ifndef MY_GLOBAL_FUN
#define MY_GLOBAL_FUN

void my_global_fun();    

#endif

In an implementation file:

#include "someheader.h"

void my_global_fun()
{
    // ...
}

In other files that require that function:

#include "someheader.h"

void f()
{
    my_global_fun();
}

Free functions like this are useful and there are not many arguments against using them. Depending on your use case, its likely appropriate to put these functions in a specific namespace to avoid name collision with other libraries you may be using.

小巷里的女流氓 2024-12-04 06:10:04

想想 main()。该功能就在那里。它不在任何类、结构或命名空间内。您只需声明并赋予它一个主体即可。当然,如果函数不是主函数,最好将原型放在标头中并在 .cpp 文件中定义它。

请记住,C 没有类,结构也不能保存成员函数。自由函数当时没有任何问题,现在也没有。

Think of main(). The function is kind of just...there. It's not within any class, struct or namespace. You just declare and give it a body. Of course, in the case of functions that are not main, it's best to put a prototype in a header and the define it in a .cpp file.

Remember, C did not have classes and structs could not hold member functions. There was nothing wrong with free functions then and there isn't now.

蘸点软妹酱 2024-12-04 06:10:04

您必须在头文件中声明其原型并在实现文件中定义它。

//file.h
void foo();

//file.cpp
void foo ()
{}

为了简短地回答您的第二个问题,当多个不同的类和类型以通用方式使用全局函数时,需要全局函数。例如数学函数。

否则,一般来说你可能会避免这么多全局函数。此外,您还应该避免使用与此类函数关联的静态本地成员或全局数据(这样您就不必担心线程安全)。

You have to declare its prototype in header file and define it in implementation file.

//file.h
void foo();

//file.cpp
void foo ()
{}

To shortly answer your second question, Global functions are needed when they are used by several different classes and types in a generic way. For example math functions.

Otherwise, in general you may avoid so many global functions. Also you should avoid having a static local member or global data associated with such function (so that you don't have to worry about thread safety).

2024-12-04 06:10:04

除了@Necrolis 的回答之外,不推荐使用静态,而是使用未命名命名空间。然而,使用未命名的命名空间和静态都会为每个翻译单元创建单独的副本,这会增加二进制文件的大小。从这个意义上来说,使用 inline 比这两者都要好。

这些解决方案允许编译器进行更多特定于使用的优化,但与源文件中的定义然后链接相比,指令缓存不太友好。

In addition to the answer by @Necrolis, the use of static is deprecated in favour of unnamed namespaces. However, use of unnamed namespaces and static both creates separate copies for each translation unit which increases the size of binary. The use of inline is better than both of these in this sense.

These solutions allow for more usage specific optimisations by compilers but are less instruction cache friendly compared to definition in a source file and then linking.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文