【发布时间】:2013-10-07 10:01:38
【问题描述】:
(在继续之前,
没有释放和编写代码中从未使用过的变量,
用于测试工具)
我写了这样的代码和这样的 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
当我把 make all ,这个消息出现:
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的定义前面添加static(但这不太可能是一个好的长期解决方案,如果只是因为你可以最终得到两个对 SIZEOF_INT 的实际值存在分歧的目标文件)。在 C++ 中,常量会被有效地处理,但是 C 会创建两个初始化变量,每个源文件一个,并且您不能将这两个源文件链接在一起。