如何在C ++中定义一个全局函数? [英] How do you define a global function in C++?

查看:4893
本文介绍了如何在C ++中定义一个全局函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

推荐答案

你需要一个正文(在 cpp 文件):

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

然后在其他地方使用:

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

或使用内联函数(不保证它将被内联,但对于小功能很有用,例如 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

函数(因此这在头中, static 强制它只存在于一个编译单元中,所以你应该避免这种情况) / p>

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

这篇关于如何在C ++中定义一个全局函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆