לדלג לתוכן

3.8 סקופ פתרון

תרגול 1 – Scope

סעיף א – הדפסת ערך לוקלי

#include <stdio.h>

void print_local() {
    int a = 10;
    printf("a = %d\n", a);
}

סעיף ב – שגיאה בגישה למשתנה לוקלי

#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 בפונקציה

#include <stdio.h>

void counter_func() {
    static int c = 0;
    c++;
    printf("c = %d\n", c);
}

סעיף ה – static גלובלי

#include <stdio.h>

static int hidden = 777;

void print_hidden() {
    printf("%d\n", hidden);
}

סעיף ו – extern לקובץ אחר

file1.c:

int shared = 42;

file2.c:

#include <stdio.h>

extern int shared;

int main() {
    printf("%d\n", shared);
    return 0;
}

קומפילציה:

gcc file1.c file2.c -o program

תרגול 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:

global my_add
section .text

my_add:
    ; קלט: eax = a, ebx = b
    add eax, ebx
    ret

סעיף ב – קוד 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;
}

סעיף ג – קימפול

nasm -f elf32 tools.asm -o tools.o
gcc -m32 -c main.c -o main.o
gcc -m32 main.o tools.o -o my_program