[英]Link error during gcc compile with makefile
(在繼續之前,
沒有代碼中從未使用過的免費和寫變量,
用於測試工具)
我寫了這樣的代碼和Makefile像這樣:
unread_two.h
#ifndef __UNREAD_TWO_H
#define __UNREAD_TWO_H
const int SIZEOF_INT = sizeof(int);
int addTwo();
unread_twomain.c
#include <stdio.h>
#include <stdlib.h>
#include "unread_two.h"
int main(int argc, char *argv[])
{
int *x;
x = (int *)malloc(SIZEOF_INT);
x = addTwo();
free(x);
return 0;
}
unread_two.c
#include <stdio.h>
#include <stdlib.h>
#include <unread_two.h>
int addTwo()
{
int *y, *z, sum;
y = (int *)malloc(SIZEOF_INT);
z = (int *)malloc(SIZEOF_INT);
*y = 3;
sum = *y + *y;
return sum;
}
生成文件
CC=gcc
CCFLAGS=-g
%.o: %.c
$(CC) -c $< $(CCFLAGS)
all: unread_two
clobber: clean
rm -f *~ \#`\# core
clean:
rm -f unread_two *.o
unread_two: unread_twomain.o unread_two.o
unread_twomain.o: unread_two.h
unread_two.o: unread_two.h
當我放入全部內容時,將顯示以下消息:
unread_twomain.o:(.rodata+0x0): multiple definition of `SIZEOF_INT'
unread_two.o:(.rodata+0x0): first defined here
collect2: error: ld returned 1 exit status
我應該解決什么問題?
您不應該在標頭中定義 SIZEOF_INT
,否則,如您所見,當將此標頭包含在多個編譯單元中時,您將獲得多個定義。 而是在標頭中聲明它,並在源文件中定義它:
// unread_two.h
extern const int SIZEOF_INT; // *declare* SIZEOF_INT
// unread_two.c
const int SIZEOF_INT = sizeof(int); // *define* SIZEOF_INT
另外,在這種特殊情況下,您可能有理由使用宏使用“舊的傻瓜”方法:
// unread_two.h
#define SIZEOF_INT sizeof(int)
實際上,您有兩個錯誤,一個是您報告的錯誤,另一個是錯誤的錯誤。
您遇到錯誤的問題是,在您包含頭文件的所有源文件中都定義了常量SIZEOF_INT
防護僅防止在同一源文件(或從技術上講是翻譯單元)中多次包含,但又不能避免在多個來源中包含相同的文件。 這意味着編譯器將在unread_twomain.o
和unread_two.o
創建SIZEOF_INT
的定義,鏈接器隨后會抱怨該定義。
解決方案是只在頭文件中聲明常量,然后在單個源文件中定義它。
另一個問題是,在main
您將x
創建為指針,並為其分配內存(順便說一句,您不應該類型轉換malloc
的返回值),然后將addTwo
的結果addTwo
該指針。 但是addTwo
不會返回指針,而是返回一個直值,因此您使指針x
指向地址6
,這與我想的不完全相同。 當您隨后嘗試釋放x
指向的內存時,這將導致未定義的行為 ,最有可能導致崩潰。
在你的程序中你不必在所有使用指針。 只需使用普通的非指針變量:
int addTwo()
{
int y = 3;
int sum = y + y;
return sum;
}
和
int main(int argc, char *argv[])
{
int x = addTwo();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.