Thread: declaration extern --- defn in function

  1. #1
    Registered User
    Join Date
    Mar 2020
    Posts
    37

    declaration extern --- defn in function

    Can I declare a variable in .h file with extern, then use it in main (a.c) BUT it gets defined in a function that exists in b.c? Said function get's called from main....

    Thanks

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,777
    No, because that variable, being non-static and having local scope, has no linkage, so trying to declare it as having external linkage in the header makes no sense.

    I suggest that you don't worry about extern: for the most part, you're only going to use it when you need to declare a global variable, and since global variables should be rare, you probably don't need to use it. In this case, you may be able to have the function return a value or use an out parameter instead.
    Last edited by laserlight; 05-12-2020 at 05:09 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 04-25-2017, 10:25 AM
  2. Replies: 1
    Last Post: 02-19-2017, 11:34 AM
  3. defn inside hash table
    By thames in forum C Programming
    Replies: 3
    Last Post: 12-08-2012, 09:03 AM
  4. about extern declaration
    By jam_fiveface in forum C Programming
    Replies: 5
    Last Post: 09-02-2008, 04:45 AM
  5. Fixing incorrect extern declaration
    By cunnus88 in forum C++ Programming
    Replies: 4
    Last Post: 03-30-2007, 03:55 PM

Tags for this Thread