我遇到了上面标题中描述的问题。这些是我的文件及其代码:
run.c:
[...] // I think it's not relevant for the problem
declarations.h:
#ifndef DECLARATIONS_H
#define DECLARATIONS_H
#include <stdint.h>
#include <stdio.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <errno.h>
[...]
struct
{
int position;
int currentNumberOfMessages;
int numberOfProcesses;
char buf[MAX_PAYLOAD_LENGTH * MAX_SLOTS];
} mySharedMemory_sct = {0, 0, 0, '0'};
struct mySharedMemory_sct *myShMem_ptr;
[...]
#endif //DECLARATIONS_H
lib.h:
#ifndef LIB_H
#define LIB_H
#include "declarations.h"
#include <stdint.h>
#include <stdio.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <errno.h>
[...]
int init (int *argc, char **argv[])
{
/**
* map the shared memory into the process
*/
if ((myShMem_ptr = mmap(NULL, sizeof(mySharedMemory_sct), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) ==
MAP_FAILED)
{
printf("Error: %s\n", strerror(errno));
return EXIT_FAILURE;
}
/**
* increment the number of running processes called by the 'run'-process
*/
myShMem_ptr->numberOfProcesses += 1; <------- ERROR
[...]
return EXIT_SUCCESS;
}
[...]
#endif //LIB_H
对于标记为“错误”的行,编译器将引发以下错误消息:
“引用不完整类型'struct mySharedMemory_sct'的指针”
并突出显示“ myShMem_ptr-> numberOfProcesses + = 1;”中的“->”。红色是问题所在。
我已经阅读了此错误消息的其他文章,但是问题原因不同(我认为),所以我还没有找到解决方案。
预先:谢谢您的帮助!
答案 0 :(得分:1)
您需要更改
struct
{
int position;
int currentNumberOfMessages;
int numberOfProcesses;
char buf[MAX_PAYLOAD_LENGTH * MAX_SLOTS];
} mySharedMemory_sct = {0, 0, 0, '0'};
到
struct mySharedMemory_sct
{
int position;
int currentNumberOfMessages;
int numberOfProcesses;
char buf[MAX_PAYLOAD_LENGTH * MAX_SLOTS];
} mySharedMemory_sct = {0, 0, 0, '0'};
让我们看一个简单的案例:
struct a {
int x;
} b;
那么我们这里有什么?我们已经声明了一个结构并将其命名为a
,因此可以使用struct a <name>
声明该结构的实例。 b
呢?好吧,这就是这种情况的一个例子。
那是什么意思?
struct a {
int x;
} b = {0};
好吧,这当然并不意味着当您创建struct a
实例时,该实例的x值将初始化为0。这仅表示对于实例b而言,这是正确的。
您尚未发布完整的代码,但是我怀疑这可能会满足您的要求:
struct mySharedMemory_sct {
int position;
int currentNumberOfMessages;
int numberOfProcesses;
char buf[MAX_PAYLOAD_LENGTH * MAX_SLOTS];
} mySharedMemory_sct = {0, 0, 0, '0'};
struct mySharedMemory_sct *myShMem_ptr = &mySharedMemory_sct;
这里要记住的重要一点是mySharedMemory_sct
和struct mySharedMemory_sct
是两个完全不同的东西。 mySharedMemory_sct
是具有 type struct mySharedMemory_sct
的变量。您可以相互独立更改名称。