每个 class 在 C 代码 (NDK) 中为自己创建静态字段

Each class create static fields for themselves in C code (NDK)

我是 C 和 NDK 的新手,在我的应用程序中我想在不同文件之间保存和共享一些数据。所以我制作了包含静态字段的 .c 文件。

当我在一个文件中使用它时效果很好,但是当我尝试在其他文件中使用它时它没有我之前在那里写的数据。看起来每个文件都在自己内部创建了我的静态字段的新实例

编辑

添加了 .h 文件。

代码test.h:

#ifndef IJKPLAYER_TEST_H
#define IJKPLAYER_TEST_H

void saveStartLoadingData();

int64_t getStartLoading();

void addToLoadingByte(int64_t bytesCount);

void endOfLoading();

void calculateAndSaveCurrentBitrate();

int64_t getDiff();

int64_t getLoadedBites();

int64_t getEndLoading();

int64_t getCurrentBitrate();

#endif //IJKPLAYER_TEST_H

test.c:

#include "test.h"
#include <time.h>

static const int64_t ONE_SECOND= 1000000000LL;

extern int64_t start_loading;
extern int64_t end_loading ;
extern int64_t loaded_bytes;
extern int64_t currentBitrate;
extern int64_t diff;

int64_t now_ms() {
    struct timespec now;
    clock_gettime(CLOCK_MONOTONIC, &now);
    return (int64_t) now.tv_sec*1000000000LL + now.tv_nsec;
}

void saveStartLoadingData(){
    loaded_bytes = 0LL;
    start_loading =  now_ms();
}

int64_t getStartLoading(){
    return start_loading;
}

void addToLoadingByte(int64_t bytesCount){
    loaded_bytes += bytesCount;
}

void endOfLoading(){
    end_loading = now_ms();
    diff = end_loading - start_loading;
}

void calculateAndSaveCurrentBitrate(){
    currentBitrate = loaded_bytes * ONE_SECOND/ diff;
    loaded_bytes = 0;
}

int64_t getDiff(){
    return diff;
}
int64_t getLoadedBites(){
    return loaded_bytes;
}
int64_t getEndLoading(){
    return end_loading;
}
int64_t getCurrentBitrate(){
    return currentBitrate;
}

现在我以这种方式将其包含到其他文件中:

#include "test.h"

编辑 2

新错误

libavformat/avio.c:430: error: undefined reference to 'getStartLoading'
libavformat/avio.c:431: error: undefined reference to 'getEndLoading'
libavformat/avio.c:432: error: undefined reference to 'getLoadedBites'

您只能包含一次.c 文件。

如果您需要在另一个 .c 或 .cpp 文件中使用该 .c 文件中的变量或函数,您必须制作一个 .h 文件并将其包含在需要变量的文件中。您可以根据需要在任意多个 .c 或 .cpp 文件中包含一个 .h 文件。

在.h文件中写入:

extern int64_t start_loading;
void saveStartLoadingData();

从 .c 文件中删除所有 static