简体   繁体   English

使用gcc编译C程序

[英]Using gcc to compile a C program

I am following an example from CUNY and I have never done anything with C before so I probably don't know what I am doing. 我正在按照CUNY的示例进行操作,并且之前从未使用C做过任何事情,所以我可能不知道自己在做什么。

Consider the program below. 考虑下面的程序。

  1. Do I need a shebang line for C code written in emacs? 我需要用shebang行编写用emacs编写的C代码吗?
  2. When I go to compile using the line gcc -g -o forwardadding forwardadding.c I am hit with the message: 当我使用gcc -g -o forwardadding forwardadding.c行进行编译时,出现以下消息:

     forwardadding.c:9:17: error: expected expression before '<' token 
  3. Once I get the code compiles, I can use gdb to debug and run the code corrrect? 编译代码后,就可以使用gdb调试并正确运行代码了吗?

The code: 编码:

#include <stdio.h>
#include <math.h>

main()
{
    float sum, term;
    int i;
    sum = 0.0;
    for( i = 1; < 10000000; i++)
    {
        term = (float) i;
        term = term * term;
        term = 1 / term;
        sum += term;
    }
    printf("The sum is %.12f\n", sum);
}
  1. No shebang is needed. 不需要shebang。 You could add an Emacs mode line comment. 您可以添加Emacs模式行注释。

  2. The for loop should be: for循环应为:

     for (i = 1; i < 10000000; i++) 

    Your code is missing the second i . 您的代码缺少第二个i

  3. Yes, you can use GDB once you've got the code compiling. 是的,您可以在代码编译后使用GDB。

You'd get a better answer to the mathematics if you counted down from 10,000,000 than by counting up to 10,000,000. 如果您从10,000,000开始倒数​​,则对数学的选择会比对10,000,000进行计数更好。 After about i = 10000 , the extra values add nothing to the result. 在大约i = 10000 ,多余的值不会为结果添加任何内容。

Please get into the habit of writing C99 code. 请养成编写C99代码的习惯。 That means you should write: 那意味着你应该写:

int main(void)

with the return type of int being required and the void being recommended. 要求使用int的返回类型,并建议使用void

You need to put a variable in the for loop for a complete expression (which is probably line 9...) 您需要在for循环中放置一个变量以获得完整的表达式(可能是第9行...)

for( i = 1; < 10000000; i++)

change to this 换成这个

for( i = 1; i < 10000000; i++)

You are missing an an i . 您缺少一个i Just correct that as Jonathan Leffler has suggested and save your file. 请按照乔纳森·莱弗勒(Jonathan Leffler)的建议修改并保存文件。 Open your terminal and just use this to compile your code gcc your_file_name.c and your code compiles next to run the code that just compiled type ./a.out and your program runs and shows you the output. 打开您的终端,然后使用它来编译代码gcc your_file_name.c然后编译您的代码,然后运行刚刚编译为./a.out类型的代码,然后程序运行并显示输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM