3.8 סקופ פתרון
תרגול 1 – Scope¶
סעיף א – הדפסת ערך לוקלי¶
סעיף ב – שגיאה בגישה למשתנה לוקלי¶
#include <stdio.h>
void define_var() {
int b = 20;
}
// int main() {
// printf("%d\n", b); // שגיאה – b לא מוגדר כאן
// return 0;
// }
סעיף ג – משתנה גלובלי¶
#include <stdio.h>
int counter = 0;
void inc() {
counter++;
}
int main() {
inc();
inc();
printf("counter = %d\n", counter); // 2
return 0;
}
סעיף ד – static בפונקציה¶
סעיף ה – static גלובלי¶
סעיף ו – extern לקובץ אחר¶
file1.c:
file2.c:
קומפילציה:
תרגול 2 – Inline Assembly¶
סעיף א – כתיבה פשוטה עם asm¶
#include <stdio.h>
int main() {
int result;
asm("movl $5, %%eax;"
"movl $2, %%ebx;"
"addl %%ebx, %%eax;"
"movl %%eax, %0;"
: "=r" (result)
:
: "%eax", "%ebx"
);
printf("result = %d\n", result); // 7
return 0;
}
סעיף ב – החלפה בין רגיסטרים¶
#include <stdio.h>
int main() {
int x = 8, y = 3;
asm("movl %0, %%eax;"
"movl %1, %%ebx;"
"xchgl %%eax, %%ebx;"
"movl %%eax, %0;"
"movl %%ebx, %1;"
: "+r"(x), "+r"(y)
:
: "%eax", "%ebx"
);
printf("x = %d, y = %d\n", x, y); // x = 3, y = 8
return 0;
}
תרגול 3 – קימפול פרויקט עם C ו־ASM¶
סעיף א – כתיבת קובץ Assembly¶
tools.asm:
סעיף ב – קוד C שמפעיל את האסמבלי¶
main.c:
#include <stdio.h>
extern int my_add(int, int);
int main() {
int result;
asm("movl $10, %%eax;"
"movl $15, %%ebx;"
"call my_add;"
"movl %%eax, %0;"
: "=r"(result)
:
: "%eax", "%ebx"
);
printf("sum = %d\n", result); // 25
return 0;
}