【问题标题】:Using nested functions in C在 C 中使用嵌套函数
【发布时间】:2014-03-26 19:37:08
【问题描述】:

我已经编写了一个由 main 调用的函数。在函数中,我有一个嵌套函数。我编译使用:

gcc -o numericalIntegration numericalIntegration.c TrapezoidRule.c SimpsonsRule. GaussQuad.c -fnested-functions

这是我的梯形规则:

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

#define pi 3.1415927

//Note: This program was taken from the first practical and adjusted for sin instead of tan(x) and the limits of integration changed to o --> pi/3

double degtorad(double);

float TrapezoidRule(int args) {


int i, j; //Loop index, Counter, Array dimension
float area, rad, Sin[args], coeff; //Return value of the function, Result array, Area, Coefficient
 //TODO: Get table of sin as in Ex. 3

        j=0;

        for (i=0; i<=180; i=i+5) {
                rad = degtorad(i);
                Sin[j] = sin(rad);
                j=j+1;
                }

        area = Sin[0];
        for (i = 1; i < args - 1; i++) {
                area = area + 2.0*Sin[i];
                }
 //Calculating the area using the trapezoid rule and comparing to the real area 
        coeff = degtorad(2.5);
       // area = (area + Sin[dim - 1]) * coeff; 

 //Function to convert degrees to radians
    double degtorad(double arg) {
        return( (pi * arg)/180.0 );
    }

        area = (area + Sin[args - 1]) * coeff;

return area;

}

我得到的错误是:

Undefined symbols:
  "_degtorad", referenced from:
      _TrapezoidRule in ccdjbt6m.o
      _TrapezoidRule in ccdjbt6m.o

ld: symbol(s) not found
collect2: ld returned 1 exit status

我做错嵌套函数了吗?

【问题讨论】:

  • 嵌套函数是 gcc 扩展——我看不出有任何理由将您的 degtorad 函数嵌套在 TrapezoidRule 中。尝试将 degtorad 函数移出文件范围。
  • 或者,尝试将嵌套函数移动到封闭函数的顶部。如果我没记错的话,嵌套函数需要在调用时使其定义可见;您拥有的文件范围前向声明不符合嵌套函数的前向声明。请参阅gcc.gnu.org/onlinedocs/gcc-4.8.1/gcc/Nested-Functions.html,尤其是最后的部分。

标签: c function gcc nested nested-function


【解决方案1】:
  1. 删除TrapezoidRule()定义前的degtorad()声明。
  2. degtorad() 的定义移动到TrapezoidRule() 的开头,或至少在调用它之前。

如果你想先声明一个嵌套函数,然后把它的定义放在包含函数的末尾,你可以这样做:

float TrapezoidRule(int args) {
    auto double degtorad(double);

    coeff = degtorad(2.5);

    double degtorad(double) {
        /* .... */
    }
}

更多详情请参阅6.4 Nested Functions

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 2011-07-18
    • 2018-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多