solved a problem about undefined / unresolved reference in c

//test.c

extern int a;

static int f(){

    return a;

}

 

//main.c

static int a=20;
int main(){

     return 0;
}

 

There will be no problem compiling this code,in msvc. In fact f() refereced a variable a defined staticly in main,c .because there is no other functions calling f(), it won't be linked.

 

 but if add g() to test.c

 

int g(){
 return f();
}

 

then msvc and intel c++ complains ahout undefined reference, because f is called by g, and g is used externally.

if we add static defination to g,then it still works. because g is used only in test.c,and no other functions called g, so it won;t be linked too.

 

if using c++ builder compiler, it is even not a problem if g is a non static function, as long as there is no other compile unit called g. 

 

under gcc, even static functions not using by any other functions will be linked. so the above code will generate an underfined error. the only exception is that if the function is decoration by static inline. but as we know inline functions is not always being inlined. such as belows:

 

static inline int f(){

    return a;

}

int (*delegate)()=f;

 

because a function referenced by a function pointer can not be inlined, so the above code can not be linked either.

### 如何避免在同一作用域中重复定义非空CVX问题导致的覆盖问题 为了避免在同一作用域中重复定义非空CVX问题而导致的覆盖问题,在编写MATLAB CVX程序时应遵循一些最佳实践。具体方法如下: #### 使用独立的作用域 每次构建新的优化问题时,应该在一个新的函数或脚本文件内执行,这样可以确保每个CVX问题是完全独立的。通过这种方式,不同问题之间不会相互干扰。 ```matlab function solve_problem_1() cvx_begin quiet variable x(2); minimize(norm(x, 1)); subject to A*x == b; cvx_end % 处理结果... end function solve_problem_2() cvx_begin quiet variable y(3); maximize(sum(y)); subject to C*y >= d; cvx_end % 处理结果... end ``` #### 清除现有变量和表达式 在重新启动一个新的CVX建模过程之前,应当清除任何先前存在的CVX对象(如变量、约束条件等)。这可以通过调用`cvx_clear`命令来完成[^1]。 ```matlab % 解决第一个问题 cvx_begin quiet variable w(n); minimize(w'*Sigma*w); subject to mu'*w >= R_target; sum(w) == 1; cvx_end disp('First problem solved.'); % 准备解决第二个问题前清理环境 cvx_clear; % 开始下一个问题 cvx_begin quiet ... cvx_end ``` #### 避免全局变量污染 尽量减少使用全局变量,并且尽可能将所有必要的输入参数传递给函数内部。这样做不仅有助于防止意外的数据共享带来的错误,也使得代码更易于理解和维护。 #### 定义唯一名称的空间 为每一个新引入的CVX变量赋予独一无二的名字,尤其是在循环结构或其他可能多次触发相同命名模式的情况下尤为重要。虽然这不是绝对必要,但在调试期间会非常有用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值