Fre*_*erJ 6 c macos gcc osx-mountain-lion
Yes, it's been asked before, but every answer I come up with on SO and elsewhere has to do with compiling C++ code in gcc instead of g++, or a issue of some kind with standard libraries. So far, nothing actually lining up right for me here.
So, I'm going through a basic crash course on C, and trying to compile an example used to illustrate linking to files that you create, rather than from the standard libraries. Here's the code:
math_functions.h
int sum (int x, int y);
float average (float x, float y, float z);
Run Code Online (Sandbox Code Playgroud)
math_functions.c
int sum (int x, int y)
{
return (x + y);
}
float average (float x, float y, float z)
{
return (x + y + z) / 3;
}
Run Code Online (Sandbox Code Playgroud)
and finally
test3.c
#include <stdio.h>
#include "math_functions.h"
main ()
{
int theSum = sum (8, 12);
float theAverage = average (16.9, 7.86, 3.4);
printf ("the sum is: %i ", theSum);
printf ("and the average is: %f \n", theAverage);
printf ("average casted to an int is: %i \n", (int)theAverage);
}
Run Code Online (Sandbox Code Playgroud)
These are all in the same folder. When I open the Terminal, cd to the folder and run:
gcc test3.c -o test3
Run Code Online (Sandbox Code Playgroud)
I get:
Undefined symbols for architecture x86_64:
"_average", referenced from:
_main in ccmf69Tt.o
"_sum", referenced from:
_main in ccxms0fF.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
This happens if I use gcc or g++ (which I shouldn't have to do, since this should all be C), and everything I've compiled before now works fine with the
#include <stdio.h>
Run Code Online (Sandbox Code Playgroud)
at the top.
I can get it to compile and run fine by removing the
#include "math_functions.h"
Run Code Online (Sandbox Code Playgroud)
from the test3.c file, putting the contents of math_functions.h before main() and the contents of math_functions.c after main(). And yes, that is copy and paste, so its definitely the same code.
So yeah, I can get my code to work, but it defeats the purpose of the exercise, in that I don't end up being able to use that code in any other C files without copying it and pasting it into the one file...
So I'm wondering, is there a way I can fix this, so I can include more that just the standard C, C++ and Objective-C libraries?
This happens through box the Terminal, manually typing out the gcc command, and through CodeRunner, which has the standard commands all tucked away into a button, so I can't stuff it.
我使用Xcode 4.6.2中的命令行工具在2012 Mac Mini上运行Mountain Lion 10.8.4(12E55)(几小时前安装它们,我实际上并没有做太多标准使用Mini直到现在)
我在MacBook Air上安装了所有相同的软件,但尚未对其进行测试,以确定是否存在相同的问题.
有什么指针吗?如果其他人已经有了这个并在SO的某处工作了,请指点我,我一直在寻找一个小时,但就像我之前说的那样,到目前为止我找到的所有解决方案最终都在那里是C++代码或标准库奇怪的东西.
你只需要编译maths_function.链接器抱怨它没有该模块中包含的定义.
gcc test3.c math_functions.c -o test3
Run Code Online (Sandbox Code Playgroud)