簡體   English   中英

連接時出現“錯誤:變量的類型不完整”問題

[英]'error: variable has incomplete type' problem with linking

我在構建一個非常基本的項目時遇到了問題。 編譯器似乎認為我沒有定義某種類型,即使該類型已明確定義。 運行make ,出現以下錯誤:

gcc -Wall -pedantic -std=c11   -c -o set.o set.c
gcc -Wall -pedantic -std=c11   -c -o driver.o driver.c
driver.c:12:9: error: variable has incomplete type 'set_t' (aka 'struct set')
  set_t hey;
        ^
./set.h:10:16: note: forward declaration of 'struct set'
typedef struct set set_t;
               ^
1 error generated.

這是我的makefile:

# Makefile for groups

PROG = driver
HEADERS = set.h
OBJS = driver.o set.o

CC = gcc
CFLAGS = -Wall -pedantic -std=c11

$(PROG): $(OBJS)
    $(CC) $(CFLAGS) $^ -o $@

driver.o: set.h set.o
set.o: set.h

.PHONY: clean

clean:
    rm -f *.o

driver.c:

#include <stdio.h>
#include "set.h"

int main (int argc, char* argv[])
{
  set_t hey;

  return 0;
}

set.h:

#ifndef __SET_H
#define __SET_H

typedef struct set set_t;

set_t* set_new();

#endif

set.c:

#include "set.h"
#include <stdlib.h>

typedef struct set {
  int size;
  void** items;
} set_t;

任何幫助將不勝感激!

如您所知,#include標頭幾乎意味着復制粘貼整個文件。

讓我們看看如果復制粘貼set.hdriver.c會發生什么:

driver.c:

#include <stdio.h>
#ifndef __SET_H
#define __SET_H

typedef struct set set_t;

set_t* set_new();

#endif

int main (int argc, char* argv[])
{
  set_t hey;

  return 0;
}

現在我們已經解決了這個問題,讓我們專注於這一行:

typedef struct set set_t;

該別名將struct set作為set_t別名,但是,由於以前在代碼中未遇到過struct set ,因此它也用作前向聲明。 讓我們使該聲明更加明顯:

struct set;
typedef struct set set_t;

前向聲明允許我們做什么? 獲取有關結構的指針。 它不允許我們做什么? 創建該類型的對象。 我們可以看到這正是我們在main要嘗試做的:

set_t hey; //attempting to create a new object, but fails because the compiler doesn't have all the necessary information about the structure
//the compiler only knows that the structure exists

每當聲明結構時,都在頭文件中聲明整個結構以及所有typedef和函數原型。 .c文件應僅包含這些函數的定義。 讓我們更正您的代碼:

driver.c:

#include <stdio.h>
#include "set.h"

int main (int argc, char* argv[])
{
  set_t hey;

  return 0;
}

set.h:

#ifndef __SET_H
#define __SET_H

typedef struct set {
  int size;
  void** items;
} set_t;

set_t* set_new();

#endif

set.c:

#include "set.h"
#include <stdlib.h>

//place all the definitions of the functions here, like that set_new() function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM