1

I have this problem with a static functions declared in a header file. Say I have this file "test.cpp":

#include <cstdlib>
#include "funcs.hpp"

...do some operations...

void *ptr = my_malloc(size);

...do some operations...

The "funcs.hpp" file contains:

#include <ctime>
#include "../my_allocator.hpp" // my_malloc is defined here as a 
                               // global static function

...some functions...

static int do_operation() {
    // variables declaration
    void *p = my_malloc(size);

   // ...other operations
}

when I compile my program, I get an error 'my_malloc' was not declared in this scope, referred to the one used in the "funcs.hpp" file, while it doesn't complain with the one used in "test.cpp".

The function in question is defined as a global static function within the header "my_allocator.hpp", and all it does is to get an instance of the allocator object and use the malloc function:

static void * my_malloc(size_t size) {
    return MYAllocator::instance()->malloc(size);
}

I'm not sure whether this problem is related to the scope of a function declared as static global inside a header, but what looks weird to me is that it complains in one case and not in the other: when I use it in a static function in a header (funcs.hpp) that includes the header where it is declared, it results in the error "not declared in this scope"; while it is OK when used from a file that includes the header "funcs.hpp". Where am I getting wrong?

4

1 回答 1

1

说明static符指定符号(变量或函数)仅在此翻译单元中可见。我认为那不是您想要的情况,因此请删除说明static符。
请注意编译器所说的:“my_malloc 未在此范围内声明”。这正是您指定的static内部链接

另请注意,该关键字的这种使用已static被弃用,取而代之的是未命名的命名空间

于 2013-09-12T16:11:26.657 回答