2015-10-18 110 views
-1

我正在使用帶有編譯器版本Apple LLVM版本7.0.0的MacBook Air(13英寸,2011年中)上的NetBeans IDE 8.0.2(Build 201411181905)(OSX 10.10.5) -700.0.72)/ Target:x86_64-apple-darwin14.5.0。無法編譯C程序

我想要編譯如下代碼: 棧/主

#include "stack.h" 
#include <stdio.h> 
#include <stdlib.h> 
/* 
* 
    */ 
int main(int argc, char** argv) { 

push(1.2); 
(void)printf("On Stack"); 


//return (EXIT_SUCCESS); 
} 

棧/ src目錄/ stack.c

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

/* initialize stack for float values */ 
static float stack[STACK_LENGTH] = { 0.0 }; 

/* 
* increase stack and push new float into stack[0] 
* params: 
* float > new value to push to position 0 
* return: 
* void 
*/ 
void push(float new) { 
    /* to do */ 
    if(pos<STACK_LENGTH){ 
     stack[pos++]=new; 
    }else{ 
     (void)printf("Stack-Overflow\n"); 
    } 
} 

/* 
* pop float at position 0 and decrease stack 
* params: void 
* return: float > value at position 0 
*/ 
float pop(void) { 
    /* to do */ 
    if(pos>0){ 
     stack[pos--]; 
    } else{ 
     (void)printf("Stack-leak\n"); 
    } 
} 

/* 
* get stack at pos 
* params: int > stack position 
* return: float > value at position pos 
*/ 
float get(int pos) { 
    /* to do */ 
    float value; 
    return value = stack[pos]; 
} 

/* 
* set float value in stack at pos 
* params: 
* float > value to set at position pos 
* int > stack position 
* return: 
* void 
*/ 
void set(float value, int pos) { 
    /* to do */ 
    stack[pos] = value; 
} 

/* 
* list stack to console 
* params: 
* void 
* return: 
* int > number of characters printed 
*/ 
int list(void) { 
    /* to do */ 
    return 0; 
} 

/* 
* clear stack 
* params: void 
* return: void 
*/ 
void clear(void) { 
    /* to do */ 
    float stack[15]= {0.0}; 
} 

棧/ src目錄/ stack.h

#ifndef STACK_H_ 
#define STACK_H_ 

/* Includes */ 
#include <stdio.h> 
#include <stdlib.h> 

/* stack size */ 
#define STACK_LENGTH 15 

/* global variables*/ 
static float stack[STACK_LENGTH]; 
static int pos = 0; 

/*function declaration*/ 
void push(float); 
float pop(); 
float get(int); 
void set(float, int); 
int list(); 
void clear(); 



#endif /* STACK_H_ */ 

當我運行這條語句時:

gcc -c demo_stack.c

我得到這個錯誤:

>fatal error: 'stack.h' file not found 
>#include "stack.h" 
>  ^
+1

編譯器告訴你他沒有足夠的信息來查找文件'stack.h'。你必須添加一個包含你的編譯器命令行的路徑。對於gcc,這通常使用'-I directoryNameGoesHere'選項完成。 –

+0

你的意思是這樣的:gcc -c -l stack/src/demo_stack.c – ishango

回答

1

正如你所看到的文件在不同的文件夾和一個編譯器不能讀你的心和你的意圖:

stack/src/stack.c 
stack/src/stack.h 
stack/main/demo_stack.c? 

首先如果要將它們鏈接在一起並生成可執行文件,則需要編譯這兩個c文件,因爲具有main()函數的文件引用功能push,該函數在stack.h中聲明,但在stack.c中定義。然後你需要告訴你的編譯器,編譯你的主文件時應該考慮包含stack.h的路徑。您的最終構建命令應該看起來像

clang -c -I../stack demo_stack.c ../stack/stack.c 
+0

我已經做了更改並創建了.o文件。現在我得到這樣的:'主根$ GCC -c demo_stack.c 根$ gcc的-o stack.exe demo_stack.o用於建築x86_64的 未定義的符號: 「_push」,從引用:在demo_stack.o LD _main :找不到x86_64架構的符號 clang:錯誤:連接器命令失敗,退出代碼1(使用-v查看調用)' – ishango

+0

明白了! gcc stack.o demo_stack.o -o demo_stack – ishango