我不知道這個問題屬於什麼,請花點時間閱讀。它涉及C和C++的區別以及編寫代碼的習慣;代碼如下: 我把它分成3個文件; 會在main.c以及安排代碼的習慣
#include"myh.h"
unit_t *paa;
int main()
{
paa=(unit_t*)malloc(sizeof(unit_t));
if(paa==NULL){
printf("out of memory\n");
exit(1);
}
fuzhi(paa);
printf("hello !%d",paa->number);
free(paa->msg);
free(paa);
paa=NULL;
return 0;
}
anohter C:ke.c
#include"myh.h"
void fuzhi(unit_t* pa)
{
pa->number=3;
pa->msg=(char *)malloc(20);
printf("fuzhi !");
}
的.h文件:myh.h
#ifndef P_H
#define P_H
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct{
int number;
char *msg;
}unit_t;
void fuzhi(unit_t* pa);
int a;
#endif
所以,問題是,當我運行用C代碼它沒有問題,但是當我將它保存爲cpp時,錯誤是'a'的多重定義;爲什麼? 第二個問題是我不知道我安排的代碼好壞的習慣。有人給我一些很好的建議嗎?當代碼很大時,我通常會將聲明放在h文件中,並使用c/cpp寫入函數的定義。然後使用主c/cpp來滿足主要功能。有人能給我一些關於編寫代碼的好建議嗎,我是一個新的學習者。 謝謝。
除非全局變量是一個C++對象,我沒有看到C和C++會有什麼不同? – Lundin
代碼風格如何?現在我通常使用3部分代碼進行編碼,當項目很大時,我需要一種風格來安排我的代碼。可以給我一些建議。謝謝。 – Fanl
@Lundin在C中查找*暫定義* –