ヘッダーファイルで宣言された構造体変数を複数のソースファイルにインクルードするにはどうすればよいですか?

Mike32ab

複数のソースファイルからアクセスできるように、ヘッダーファイルで宣言および定義された構造体変数が必要ですが、リンカーエラーが発生します。ここに小さなソースコードを入れています。リンカーエラーは

main.obj:エラーLNK2005:_aはlibrary.objですでに定義されています

致命的なエラーLNK1169:1つ以上の複数定義されたシンボルが見つかりました

header.h

struct Student {
    char *FirstName;
    char *LastName;
};

struct Student a = {"John", "Jackson"};

library.c

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

void PrintStudentName(struct Student *name)
{
    printf("%s\n%s\n", name->FirstName, name->LastName);
}

main.c

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


void PrintStudentName(struct Student *name);

int main()
{
    PrintStudentName(&a);
    return 0;
}
セルゲイ・カリニチェンコ

ヘッダーのこの定義行を置き換える必要があります

struct Student a = {"John", "Jackson"};

この宣言で:

extern struct Student a;

これは、タイプのグローバル変数を宣言しますstruct Student

定義をCファイルの1つに移動して、修正を完了します。

// This goes into one of the C files, does not matter which one.
struct Student a = {"John", "Jackson"};

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ