Thread: confusion on the difference between external and static

  1. #1
    Registered User
    Join Date
    Jan 2024

    confusion on the difference between external and static


    I know that external variables are seen by every function in every file of the program and static variables (do they have to be declared in a function body or can they be declared outside?) are only seen by functions in the same file where they were declared.
    I want to see the difference between extern and static - in my mind the first two functions should work but the 3. should not because the static variable is not visible in the add1() function as it is declared in another file.

    Can someone tell me if I am right? If so what needs to happen so that my Makefile compiles. Thanks! :-)

    //file computesize.c
    #include <stdio.h>
    #include "functionimporttest.c"
    void add1(int a, int b);
    void add1(int a, int b){
      printf("%s%d\n", "add function from computesize.c", a + b);
    main() {
      add(glob, 1);
      add(static_int, 1);
      add1(static_int, 1);
    // file functionimporttest.c
    #include <stdio.h>
    int glob = 3;
    void add(int a, int b);
    void add(int a, int b){
      static int static_int = 5;
      printf("%s%d\n", "add function from functionimporttest", a + b);
    test: computesize.c
        $(CC) computesize.c functionimporttest.c -o testprogram -Wall

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > #include "functionimporttest.c"
    Most of your confusion comes from this.

    Including .c files is 99% the wrong thing to be doing.

    You need
    #include "functionimporttest.h"

    Where the .h file contains
    extern int glob;
    void add(int a, int b);
    functionimporttest.c also needs
    #include "functionimporttest.h"
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. difference between static int a and int static a?
    By albert3721 in forum C Programming
    Replies: 18
    Last Post: 12-07-2007, 11:34 AM
  2. diff b/w static & external variables
    By able in forum C Programming
    Replies: 3
    Last Post: 05-05-2006, 05:00 PM
  3. static variables confusion
    By Kleid-0 in forum C Programming
    Replies: 6
    Last Post: 01-08-2005, 06:11 PM
  4. Replies: 2
    Last Post: 10-02-2004, 10:12 AM
  5. Keeping track of static external structure
    By pwilfred in forum C Programming
    Replies: 6
    Last Post: 03-13-2003, 06:23 PM

Tags for this Thread